'Getting wrong output in C program [closed]
Expected output : "total is equal to 114"
Current output : "total is equal to -334"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define SZ 3
int main(void) {
int i, one = 0, two = 0, total = 0;
printf(
"Enter two whole numbers separated by a space: "); // user enters 56 2
total = scanf("%d %d", &two, &one);
for (i = 0; i < SZ; i++) {
if (i / two) {
total = two + one / total;
} else {
total -= one * two;
}
}
printf("total is equal to %d\n", total);
return 0;
}
Solution 1:[1]
if(i / two) is always false:
- 1st iteration
->0 / 56 = 0 - 2nd iteration
->1 / 56 = 0.02which is treatead asint, so0 - 3rd iteration
->2 / 56 = 0.04same as before
Given the above, and knowing that 0 is false, only the else block is executed 3 times, since scanf returns the number of read inputs, which is 2, and you assign it to total, total begins with the value 2, so:
2 -= 56 * 2 is -110
-110 -= 56 * 2 is -222
-222 -= 56 * 2 is -334
And that's how you get that value.
As for the 114 value you want, it's not clear how or for what reason or logic it should be achieved.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
