-1
main()
{
    float a=10;
    float c;
    float b=5.5;
    c=a+b;
    printf("%d",c);
}

The output of the above code is zero.Why is that? I am sorry if that is some really simple C concept, I am kind of a beginner.

Paritosh
  • 11,144
  • 5
  • 56
  • 74
user2715898
  • 921
  • 3
  • 13
  • 20
  • It's undefined behaviour. You're lying to the compiler. (I once answered a [similar question](http://stackoverflow.com/a/7295097/596781).) – Kerrek SB Aug 25 '13 at 17:42

2 Answers2

5

You need to use %f (or %e or %g, depending on your preferred format) instead of %d for floating-point numbers. Indeed, using %d for non-integers is "undefined behaviour".

printf("%f", c);

Alternatively, if you're trying to round the floating-point to an integer, you must cast it first.

printf("%d", (int) c);
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
0

See a+b=c will result c to become 15.5 when you try to printf c as a decimal "%d" it will be "undefined behaviour" as Chris said. If you do printf("%d",(int)c); your out put will become 15 and if you printf("%f",c); you will get 15.5

Nxtmind
  • 57
  • 8