Checking

May 12, 2013 at 1:02pm
This is supposed to check for a type of number input by user. For any number put in a and zero in b it says the same thing (Number is real). I would also like to make a and b variables of type double, but the compiler complains about double in % operator. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main() {
    int a, b; cin >> a >> b;
         if(a > 0 && a % 10 == 0 && b == 0) cout << "Number is natural!\n";
    else if(         a % 10 == 0 && b == 0) cout << "Number is an integer!\n";
    else if(                        b == 0) cout << "Number is real!\n";
    else if(                        b != 0) cout << "Number is complex!\n";
    else                                    cout << "Bad input\n";
    return 0;
}
May 12, 2013 at 1:12pm
% only works for integers. Floating point values can't be used with %.

It's pretty hard telling if a double is an integer or not due to how it's stored, if you enter 1000, it may be stored as 999.99999999213 or something like that.

What you can do is use std::to_string to convert the double to a string, and then search for a '.' or a '-'...
Last edited on May 12, 2013 at 1:14pm
May 12, 2013 at 2:15pm
The <cmath> library has many functions available to make this a very simple task.

You can split a floating-point value into its integer and fractional parts using the modf() function.
http://www.cplusplus.com/reference/cmath/modf/

You might also test whether number == floor(number) as a test for an integer value.
http://www.cplusplus.com/reference/cmath/floor/

There is also the function fmod() which gives the remainder of a division.
http://www.cplusplus.com/reference/cmath/fmod/
Last edited on May 12, 2013 at 2:16pm
Topic archived. No new replies allowed.