I was working on some 'determine the output' questions in C. I came across this question which looked simple on the face of it, but after running the code left me puzzled.
The output I expected was "True". However upon running, it was "False". And when I checked the value of f using printf(), it showed 0.1. Can someone please explain why f being assigned 0.1 doesn't return true for the IF statement?
There was no explanation for the answer from where I picked the question up, and I wasn't able to find an answer myself.
#include <stdio.h>
int main()
{
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
}
The problem is that variable f
defined as having type float
while float constant 0.1
has type double
. Type double
has more precision than type float
. it has more binary digits to represent fraction. So in this statement
float f = 0.1;
there is a truncation.
To get the expected result you should write at least
if (f == 0.1f)
Also that to be sure that there is no rounding the code should look as
#include <stdio.h>
int main( void )
{
float f = 0.1f;
if ( f == 0.1f )
printf("True\n");
else
printf("False\n");
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments