Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if given number is integer

Tags:

c++

numbers

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?

like image 932
dato datuashvili Avatar asked Oct 04 '11 10:10

dato datuashvili


2 Answers

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

like image 167
tenfour Avatar answered Sep 18 '22 15:09

tenfour


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;
 }
}
like image 43
Anirudh Prabhakaran Avatar answered Sep 18 '22 15:09

Anirudh Prabhakaran