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?
#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).
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With