main(){
float a = 0.7;
if(a%26lt;0.7){
printf("is c working");
}
else
printf("s, it's working");
getch();
}
normally result should be else block("s, it's working") but the result is "is c working"
and it's only for 0.7 value but not for the other values.
Is it the fault in c or any logic behind this
can any one tell me the reason behind this extraordinary program.
Here is a question in c. can any body tell me logic behind this program?
It is actually a bit tricky, but the problem is that 0.7 is not a float and thus the expression is not evaluating as it should.
If you change the statement to
if( a %26lt; (float)0.7 )
then it will work as it should.
The other way around this is to just create a new float and assign the value 0.7 to it, then it will definitely work correctly.
Reply:The problem is in how the compiler "casts" the value. Make an explicit cast and it will always work.
Reply:It is possibly comparison of float with the double type in (a%26lt;0.7). You might want to use the "fabs" function during comparison. You might also want to use the suffix "f" to both the 0.7s and see how it behaves.
Reply:Floats in C or any other programming language are not exact. Even if you set the value in a to 0.7 the computer will convert it to 0.7 +or- .0000000000001 or something similiar. Add a line to print value of a to see what it is and then you will understand floating point precision.
This is an issue that all programmers face because processors do everything in interger format.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment