-3

i wrote a function that check if the variable is integer or not but if I put double or float it give me that it`s integer can anyone help me

    bool check(int a) {
    if (a == (int)a) {

        cout << "integer" << endl;
        
    }
    else {
        cout << "not integer" << endl;
    }
    return 1 ;
}

void main() {
    int a;
    cout << "enter a number" << endl;
    cin >> a;
    check(a);
}
prapin
  • 6,395
  • 5
  • 26
  • 44
Tomf Tomf
  • 5
  • 2
  • 1
    https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it – πάντα ῥεῖ Mar 09 '22 at 17:09
  • 5
    `a` is *always* an integer, because you defined it as `int` variable in both places. What kind of input do you expect user to provide? – Yksisarvinen Mar 09 '22 at 17:09
  • The general gist of the input problem: a floating point number is a valid integer right up to the decimal point. The parser stops at the ., calls the function on what it read, and leaves the . and fractional portion in the stream for the program do deal with in the future. – user4581301 Mar 09 '22 at 17:16
  • 1
    Note that the function in the question is a non-portable way of writing the standard-library function [`std::isalpha`](https://en.cppreference.com/w/cpp/string/byte/isalpha). – Pete Becker Mar 09 '22 at 18:13
  • I rolled back last edit because it was completely changing the question. Don't do that, in particular when there is already an answer. – prapin Mar 09 '22 at 18:50

1 Answers1

3

You are taking in an integer value as an argument:

bool check(int a) // int a

So for example, if you pass in 3.12 into check(), then it will get converted to 3. That's why:

a == (int)a

.. will mean:

3 == (int)3 // true

..while to get the correct result, it should be:

3.12 == (int)3 // false

So to fix your issue, just change the parameter type:

bool check(double a)

..and also the input variable type:

double a;

Samples:

enter a number
3
integer
enter a number
3.12
not integer
The Coding Fox
  • 1,488
  • 1
  • 4
  • 18