cdummy
cdummy

Reputation: 455

How this printf works in this program -clarification in c?

Need some clarification...

Why do I get 2.50 0 0 0.0 as output?

#include<stdio.h>
int main()
{
    float a=5.0,b=2.0;
    printf("%f %d\n",a/b,a/b);
    printf("%d %f",a/b,a/b);
    return 0;
}

Upvotes: 1

Views: 166

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477580

You are causing undefined behaviour, since the type of a/b is (promoted to) double, which does not match the format specifier %d (which expects an int).

(The reason you see 0 is probably because the sizeof(int) bytes you happen to be accessing are all zero, being part of the (very short) mantissa of a simple number like 2.5, and your platform stores floating point numbers as IEEE754 in little endian order:

    |        <-- * -->         // * = sizeof(int)
400 | 4 0000 0000 0000         // == 2.5
S+E | Mantissa

Try 2./5. to see some other results.)

Upvotes: 4

Related Questions