here 'a' should get printed according to me as the condition (0.7<0.7) is false but 'c'Code:#include<stdio.h>
void main()
{
float a=0.7;
if(a<0.7)
printf("c");
else
printf("a");
}
is printed instead can somebody please explain?
Printable View
here 'a' should get printed according to me as the condition (0.7<0.7) is false but 'c'Code:#include<stdio.h>
void main()
{
float a=0.7;
if(a<0.7)
printf("c");
else
printf("a");
}
is printed instead can somebody please explain?
That's because floating point values cannot always be represented exactly...
Try this...
What did it print for the actual value of a?Code:#include<stdio.h>
int main( void ) // the correct form of main
{
float a = 0.7;
prinf("a = %f\n", a);
if(a < 0.7)
printf("c");
else
printf("a");
return 0; // error level returned to OS.
}
And even better you've got two different approximations running around -- 0.7 is a double, while a is a float, hence is rounded to a different number of bits.
The default data type for floating point numbers in C is double, so if you don't specify when your double gets demoted to a float for comparison you loose accuracy. Try this instead:
Code:int main(void){
float a = 0.7;
if(a < 0.7f)
printf("boo");
else
printf("yeah");
getchar();
return (0);
}
:cool::cool: andrew hunters code is working..yeah!!