Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   can u answer Y? (http://www.go4expert.com/forums/answer-y-t11777/)

shanku_4ch 1Jul2008 21:43

can u answer Y?
 
Quote:

#include<stdio.h>
#include<conio.h>
void main()
{
float a=0.7;
if(a<0.7)
printf(" C ");
else
printf("c++");
getch();
}
this program gives output as :
C
why?
--------------------------------------------------------------

i browsed and found a answer saying
(c<0.7) 0.7 is double by default & variable c is float so the condition turns true
then it must be true for all values but if i use

c=0.8/*or 0.007 or 0.223*/
if(c<0.8/*0.007 or 0.223*/)

it prints C++


i want answer for this!!!!

shabbir 2Jul2008 09:10

Re: can u answer Y?
 
Check to see if the value of a is 0.6999999999999

simcopter 3Jul2008 02:45

Re: can u answer Y?
 
you are running into a precision issue between floats and doubles. The easiest way to fix it is to add a 'f' to the literal telling the compiler to store it as a float. the code should work then.

Code:

#include<stdio.h>
#include<conio.h>
void main()
{
float a=0.7f;
if(a<0.7f)
printf(" C ");
else
printf("c++");
getch();
}

this should work as you would expect.

The import take away is that when comparing floats and doubles it gets muddy if the numbers are really close together because of the different number of significant bits for each type.

shanku_4ch 3Jul2008 07:37

Re: can u answer Y?
 
but the same program gives other output if i use other values other then 0.7


All times are GMT +5.5. The time now is 13:38.