I'm new to programming and I'm learning about loops and if-else statements. For the code below, I need an explanation about why the final output is 114
when I run it in VSCode. I know that for the third iteration, since i
=2, 2%2
is false, so it goes to the else section. one * two
is supposed to be equal to 112. How did this become 114?? I know that total+= one*two
is supposed to be total = total + one*two
right? That's the definition of +=
operator. I just can't figure out why the output is 114 here. ChatGPT cant even answer.
#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", &one, &two);
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;
}
I expected the code to get the output of 116 but it always gets the 114 answer. I've already corrected the condition.
It is the order of math operations. C++ follows the standard math operations that you would see in math.
should be..