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