1

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; } 
6
  • Why are you storing into int? Commented Mar 19, 2012 at 21:40
  • 5
    The mismatched parameters in your printf statements will result in Undefined Behavio(u)r - there is nothing further to explain. Commented Mar 19, 2012 at 21:42
  • 1
    @Mysticial: Your edit changed the meaning of the question (though both versions have undefined behavior). Commented Mar 19, 2012 at 21:57
  • @KeithThompson I think my initial edit crossed with the OP's. I'm 100% sure it was originally int. I'll fix that then. Commented Mar 19, 2012 at 22:01
  • The edit history says it was originally float. Commented Mar 19, 2012 at 22:03

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@CarlNorum: Hm, the question got edited... Now I don't know but the OP's described behaviour suggests that a/b gets passed as a double (at least after the variadic standard promotion).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.