1

When I use the following code, the output result is 0 when adding the sum in the printf function, but when I add the printf function it should be printf("test: %d", c/ 2);The output is 1, Why?

int main() {
    float a = 1.5;
    int b = 2;
    int c = a + b;
    printf("test: %d", (a+b)/ 2);
}
Seraphine
  • 29
  • 2
  • 2
    Duplicate here: [Implicit type promotion rules](https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules). Basically if one operand is float and the other int, the int will get promoted to float. – Lundin Sep 02 '22 at 11:29

1 Answers1

5

Since you assign the result of a + b to an int variable, its result will be truncated.

So while the result of 1.5 + 2 is 3.5, the result assigned to c will be the integer 3.

And since both c and 2 are int values the result of c / 2 will be an int which will be truncated. So the result of 3 / 2 will simply be 1.


With the edit and the new print:

printf("test: %d", (a+b)/ 2);

Because one of the values involved in the expression a + b is a float, the result will be a float. And because of that the result of the division will also be a float.

The result of (a + b) / 2 will be a float. But since it's passed as an argument to a variable-argument function like printf it will be promoted to a double. So your statement is essentially equivalent to:

printf("test: %d", (double)((a+b)/ 2));

Now for the big problem: The %d format specifier expects an int value. Mismatching format specifier and argument type leads to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621