14

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?

4
  • 1
    I don't even... Why do you consider >20000 and <-20000 not integers? Why would you start comparing in the middle of your range and not from -20000? Commented Oct 4, 2011 at 10:38
  • yes you are right i have changed it by MAX_INT and MIN_INT Commented Oct 4, 2011 at 10:45
  • no @tenfour,i am reading section about number theory where it is discussed topics about (quadratic)residue and roots of prime numbers residues and so on,and here is algorithm which somehow involves term of integer,if square root from something is integer,then it is root ,so it is main reason Commented Oct 4, 2011 at 10:49
  • 2
    Readers: There is a new and very comprehensive Q&A on this topic, explicitly considering C++11. Commented Aug 10, 2015 at 20:21

9 Answers 9

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

Sign up to request clarification or add additional context in comments.

4 Comments

This may not work if this floor is the double floor(double) defined in <math.h>. The call to this floor will cast k to a double and the function will return the floor as a double. It would be better to use float floorf(float) here, and even better to use std::floor(float) from <cmath>.
Another potential problem area is negative numbers, where floor rounds away from zero. Safest solution is return std::floor(std::abs(k)) == std::abs(k).
Why would that cause a problem? If it's integral, it won't be rounded. If it is not integral, it doesn't matter where it gets rounded as long as it's not equal to the original, which it can't be.
This returns true for std::numeric_limits<float>::infinity()
12

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

3 Comments

Note that this returns false for sufficiently large integers (like 1e100). (Not saying that what the user wants is in fact possible in a general sense with floats.)
True (except that you can't actually represent 1e100 as a single precision float !) - I imagine it's good enough for > 99% of use cases though.
@Mat: in fact it has undefined behavior for sufficiently large values of k (greater in magnitude than about INT_MAX).
5

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.

2 Comments

Also, recursion should be avoided here and it's a very slow method, not just that x+/-1==x for |x| -> inf.
... and will cause a stack overflow in almost every case.
1

its in limit.h macro set to INT_MAX (for maximum) or INT_MIN (for minimum ) for the integers

correct answer

 bool integer(float k)
    {
        if( k == (int) k) return true;
        return false;
    }

2 Comments

Are you actually suggesting he use these constants in his function? Did you see what it does?
No, user is asking for the upper and lower limit.. :-/ so I gave the answer accordingly..
1

We could use the trunc method from math.h

#include <math.h>

inline bool IsInt(float n)
{
    return !(n - trunc(n));
}

Comments

1

I thought of a simpler way.
Consider a float number, say 1.5. The floor of this number (i.e. 1) and the ceiling of this number (i.e. 2) are different. This is true for any value having a decimal part in it.
On the other hand, an integer has both the floor and ceil values as the same. So, it'll be easy to check the ceil and floor values of the number, and hence, see if it is an integer.

#include <cmath>

bool is_integer(float n){
 int c = ceil(n);
 int f = floor(n);
 if(f==c){
  return true;
 } else {
  return false;
 }
}

Comments

0

You can just use the boost lexical cast header

  bool isinteger(float k){
  try{ 
      int tmp = boost::lexical_cast<int>(k);
      (void*) tmp;
      return true;
  }catch(boost::bad_lexical_cast &c){
  return false;
  }  

1 Comment

boost function is interested
0

Below is a working code for your question.

bool isInteger( double num ) {
    int n = int(num);
    return (num - n == 0);
}

Now I will try to explain my code with the help of 2 corner case examples.

Case 1: Given number to check = 1.10. Thus num = 1.10 and n = 1. But now, num - n = 0.10 and this is not equal to 0. Hence the code results in false!

Case 2: Given number to check = 1. Thus num = 1 and n = 1. But now, num - n = 0 and this is equal to 0. Hence the code results in true!

3 Comments

Hello, could you add explaination to your answer ?
While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. From How to Answer: "Brevity is acceptable, but fuller explanations are better."
Okay, thanks guys, I will add some comments to it then!
-1

Well, why not just this??

#include <iostream>
using namespace std;
bool is_integer(float check){
        if (int(check) == check)
                return true;
        else return false;
}
int main()
{
        float input;
        cin >> input;
        if (is_integer(input))
        cout << endl << "It's an integer";
        else cout << endl <<" Not an integer";
        return 0;
}

2 Comments

The gist of your answer int(check) == check is already present in other answers and doesn't add anything new
Ok! My fault, I didn't saw the other posts. -_-