Using the int type in the printf function does not add the same value as the float type

Viewed 42

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);
}
1 Answers

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 if 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.

Related