Testing if given number is integer
#include <cmath>
bool is_integer(float k)
{
return std::floor(k) == k;
}
This solution should work for all possible values of k
. I am pretty sure this is a case where you can safely compare floats using ==
.
Try to thoughtfully name functions. integer
does not give any clue what it actually does, so I changed the function name to something more meaningful.
For the future, testing if a number is integer should feel like a very simple operation, so you should have a strong feeling that the best solution will be very simple. I hope you realize your original solution is absurd for many reasons (biggest reason: it will cause a stack overflow for the vast majority of cases).
This is not going to work, as for sufficiently large floats, x-1 == x
.
You should test the bit pattern of the float to check whether the fractional part is 0.
Why not just do something like this:
bool integer(float k)
{
return k == (float)(int)k;
}
?
(Feel free to use proper C++ type casts of course.)