I'm trying to check if a number of a double type is integer. In here, there are several methods. I've picked up one of them but the method is working just fine without a loop. Once I put it inside a loop, it works with some numbers and fails to check other. This is the code
#include <iostream>
#include <cmath>
bool IsInteger(double x) {
return std::fmod(x, static_cast<decltype(x)>(1.0)) == 0.0; // Test if fraction is 0.0.
}
int main(int argc, char* argv[])
{
for (double i(0); i <= 4.0; i += 0.2 )
if ( IsInteger(i) )
std::cout << i << " " << IsInteger(i) << std::endl;
return 0;
}
The preceding code works with 0.0
and 1.0
but fails to verify 2.0
and 3.0
. The code is running in Windows 7 and the compiler is the visual studio. I am Ok with boost if there is a function regarding this matter.