Oct 16, 2002 #1 chaawuu Programmer Oct 16, 2002 1 US suppose i have: int a = 12; int b = 19; float c = a / b; The value for c is a float. How would I test whether or not it was an integer, or a whole number?
suppose i have: int a = 12; int b = 19; float c = a / b; The value for c is a float. How would I test whether or not it was an integer, or a whole number?
Oct 16, 2002 #2 qednick Programmer Jul 26, 2002 516 US You can use the floor() function: first you need to #include "math.h" in the appropriate header file. What floor() does is return the integer value of a double/float. Therefore: double d = 123.456; double e = floor(d); // the value of e is now 123.0 So... in this context, you can check whether a double/float has an integer value: if (d == floor(d)) { // we know that d is a whole integer } To get the fractional part of a double/float you could: double d = 123.456; double fPart = d - floor(d); // the value of fPart is now 0.456 A similar function called ceiling() will return the next highest integer value above a double/float: double d = 123.456; double c = ceiling(d); // the value of c is now 124.0 Now, just to add the icing on the cake so to speak, try to use doubles instead of floats. They tend to be more accurate. Upvote 0 Downvote
You can use the floor() function: first you need to #include "math.h" in the appropriate header file. What floor() does is return the integer value of a double/float. Therefore: double d = 123.456; double e = floor(d); // the value of e is now 123.0 So... in this context, you can check whether a double/float has an integer value: if (d == floor(d)) { // we know that d is a whole integer } To get the fractional part of a double/float you could: double d = 123.456; double fPart = d - floor(d); // the value of fPart is now 0.456 A similar function called ceiling() will return the next highest integer value above a double/float: double d = 123.456; double c = ceiling(d); // the value of c is now 124.0 Now, just to add the icing on the cake so to speak, try to use doubles instead of floats. They tend to be more accurate.
Oct 17, 2002 #3 victorv Vendor Aug 20, 2002 862 IT hi, another trik is to test the remainder of integer division: if( a%b ) there is a remainder or int a,b,x float f .... x=a/b f=(float)a / (float)b if( (float)x!=f ) f had decimal part bye Upvote 0 Downvote
hi, another trik is to test the remainder of integer division: if( a%b ) there is a remainder or int a,b,x float f .... x=a/b f=(float)a / (float)b if( (float)x!=f ) f had decimal part bye