13

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

#include <iostream>
#include <typeinfo>
using namespace std;
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);
   else 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;
       return 0;

}

So the idea is that,if a number is an integer, does not matter if it is a 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?

Danko Valkov
  • 1,038
  • 8
  • 17
  • 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? – tenfour Oct 04 '11 at 10:38
  • yes you are right i have changed it by MAX_INT and MIN_INT –  Oct 04 '11 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 –  Oct 04 '11 at 10:49
  • 2
    Readers: There is a new and [very comprehensive Q&A on this topic](http://stackoverflow.com/q/26341494/2778484), explicitly considering C++11. – chappjc Aug 10 '15 at 20:21

9 Answers9

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

tenfour
  • 36,141
  • 15
  • 83
  • 142
  • 1
    This may not work if this `floor` is the `double floor(double)` defined in ``. 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 ``. – David Hammen Oct 04 '11 at 11:11
  • 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)`. – David Hammen Oct 04 '11 at 11:15
  • 8
    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. – tenfour Oct 04 '11 at 11:17
  • This returns true for `std::numeric_limits::infinity()` – WorldSEnder Jan 23 '18 at 10:27
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.)

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 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.) – Mat Oct 04 '11 at 10:40
  • 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. – Paul R Oct 04 '11 at 10:49
  • 1
    @Mat: in fact it has undefined behavior for sufficiently large values of `k` (greater in magnitude than about `INT_MAX`). – Steve Jessop Oct 04 '11 at 11:18
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.

quant_dev
  • 6,181
  • 1
  • 34
  • 57
1

We could use the trunc method from math.h

#include <math.h>

inline bool IsInt(float n)
{
    return !(n - trunc(n));
}
Gautham
  • 766
  • 7
  • 15
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;
 }
}
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;
    }
Aman Agarwal
  • 727
  • 6
  • 15
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!

  • Hello, could you add explaination to your answer ? – CharybdeBE May 20 '21 at 15:04
  • 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 [answer]: _"Brevity is acceptable, but fuller explanations are better."_ – Pranav Hosangadi May 20 '21 at 20:40
  • Okay, thanks guys, I will add some comments to it then! – mahaturbotorque May 21 '21 at 08:17
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;
  }  
Benedikt Bergenthal
  • 495
  • 1
  • 7
  • 20
-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;
}