Search code examples
c++floating-pointnumbers

Testing if given number is integer


I am trying to implement a function which tests if a number is an integer:

#include <iostream>
#include <typeinfo>

bool integer(float k) {
    if (k == 20000) return false;
    if (k == -20000) return false;
    if (k == 0) return true;
    if (k < 0) return integer(k + 1);
    if (k > 0) return integer(k - 1);
    return false;
}

int main() {
    float s = 23.34;
    float s1 = 45;
    cout << boolalpha;
    cout << integer(s) << endl;
    cout << integer(s1) << endl;        
}

So the idea is that if a number is an integer, it does not matter if it is negative or positive. If we decrease or increase it by one, we must get zero, but the problem is, that how can we create upper and lower bounds for increasing and decreasing?


Solution

  • #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).