laura said:
Hi,
I have a variable of type double.
I need to know if there is an integer number store there. How can I
test that ?
I also have a default precision for doing this operation.
In addition to the following kind of test, think about whether the
ceil() or floor() functions might provide you a test. Consider whether
using them leads to a more reliable test or a more efficient one.
The newer functions round(), trunc(), rint, and nearbyint() might also
provide you with suitable tests. The rint() might be what you want,
since it raises the "inexact" floating point exception if the argument
is not an integer. You might find that learning how to handle floating
point exceptions is not what you want to be doing now, though. If you
do, check your text for a discussion of the <fenv.h> header. If your
implementation does not provide such a header, then don't bother.
#include <stdio.h>
#include <math.h>
int main(void)
{
int i;
double base = 4080., testv, intpart, fraction;
for (i = 2; i <= 20; i++) {
testv = base / i;
printf("Testing %g: ", testv);
fraction = modf(testv, &intpart);
if (fraction) {
printf("fractional part = %g\n"
" so probably not an integer.\n"
"integer part = %g.\n\n", fraction, intpart);
}
else {
printf("fractional part test == 0,\n" " so an integer.\n"
"integer part = %g.\n\n", intpart);
}
}
return 0;
}
Testing 2040: fractional part test == 0,
so an integer.
integer part = 2040.
Testing 1360: fractional part test == 0,
so an integer.
integer part = 1360.
Testing 1020: fractional part test == 0,
so an integer.
integer part = 1020.
Testing 816: fractional part test == 0,
so an integer.
integer part = 816.
Testing 680: fractional part test == 0,
so an integer.
integer part = 680.
Testing 582.857: fractional part = 0.857143
so probably not an integer.
integer part = 582.
Testing 510: fractional part test == 0,
so an integer.
integer part = 510.
Testing 453.333: fractional part = 0.333333
so probably not an integer.
integer part = 453.
Testing 408: fractional part test == 0,
so an integer.
integer part = 408.
Testing 370.909: fractional part = 0.909091
so probably not an integer.
integer part = 370.
Testing 340: fractional part test == 0,
so an integer.
integer part = 340.
Testing 313.846: fractional part = 0.846154
so probably not an integer.
integer part = 313.
Testing 291.429: fractional part = 0.428571
so probably not an integer.
integer part = 291.
Testing 272: fractional part test == 0,
so an integer.
integer part = 272.
Testing 255: fractional part test == 0,
so an integer.
integer part = 255.
Testing 240: fractional part test == 0,
so an integer.
integer part = 240.
Testing 226.667: fractional part = 0.666667
so probably not an integer.
integer part = 226.
Testing 214.737: fractional part = 0.736842
so probably not an integer.
integer part = 214.
Testing 204: fractional part test == 0,
so an integer.
integer part = 204.