hi i am using unix cygwin compiler, courtesy of NUS.
i know we can use if statements to compare integers but how about decimals(just as they are) ??? Thank you and sorry if this is a petty question.
hi i am using unix cygwin compiler, courtesy of NUS.
i know we can use if statements to compare integers but how about decimals(just as they are) ??? Thank you and sorry if this is a petty question.
You want to use a float type, otherwise it is the same.
HOWEVER, there is a caveat with comparing floats. Because of the nature of floating point numbers in a computer, they are only exactly equal to decimal values that are an inverse power of two -- 0.5, 0.25, 0.125, 0.0625, and so on. Notice 0.1 is not on the list.
Try this:
It does not do what you would think:Code:#include <stdio.h> int main() { float i; for (i=0.0f; i<20; i+=0.1f) { printf("%f\n",i); } return 0; }
[...]
2.500000
2.600000
2.700000
2.799999
2.899999
2.999999
[...]
So much for 0.1! This happens at different points for 32-bit and 64-bit systems.
Because of that, use a range instead of ==:
Instead ofCode:float x; [...] if (x >= 10.1999 && x <= 10.2001)
Code:if (x == 10.2)
Last edited by MK27; 05-15-2011 at 09:49 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge