Reputation: 43
Can somebody explain the output of the following code: http://cpp.sh/9dy44
Why is the last line always 0.17?
float a = 17, b = 100;
printf("%f\n", 17/100);
printf("%f\n", a/b);
printf("%f\n", 17/b);
printf("%f\n", 17.0f/b);
printf("%f\n", a/100);
printf("%f\n", a/100.0f);
printf("%f\n", 5/100);
output
0.000000
0.170000
0.170000
0.170000
0.170000
0.170000
0.170000
Upvotes: 0
Views: 1577
Reputation: 336
Because You are dividing integers and than trying to print (the integer result as) a float value
Try This
// Example program
#include <stdio.h>
int main()
{
float a = 17, b = 100;
printf("%f\n", 17.0/100);
printf("%f\n", a/b);
printf("%f\n", 17/b);
printf("%f\n", 17.0f/b);
printf("%f\n", a/100);
printf("%f\n", a/100.0f);
printf("%f\n", 5.00/100);
return 0;
}
Upvotes: 0
Reputation: 40491
This is called Undefined Behaviour
, don't try to understand why this is happening , because as the name suggests , it is undefined
!. The undefined behaviour happens because you are trying to print a double but you're passing two integers . Note that you are also getting a warning :
14:25: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
Change last line to this:
printf("%f\n", 5.0/100);
And it will work as expected .
Upvotes: 2