Is there a way to check if a variable is a whole number? C++

前端 未结 7 716
北恋
北恋 2020-12-20 14:01

I need to check if a variable is a whole number, say I have the code:

double foobar = 3;
//Pseudocode
if (foobar == whole)
    cout << \"It\'s whole\";         


        
相关标签:
7条回答
  • 2020-12-20 14:21

    You are using int so it will always be a "whole" number. But in case you are using a double then you can do something like this

    double foobar = something;
    if(foobar == static_cast<int>(foobar))
       return true;
    else
       return false;
    
    0 讨论(0)
  • 2020-12-20 14:24

    just write a function or expression to Check for whole number, returning bool.

    in usual definition i think whole number is greater than 0 with no decimal part.

    then,

    if (abs(floor(foobar) )== foobar)
        cout << "It's whole";
    else
        cout << "Not whole";
    
    0 讨论(0)
  • 2020-12-20 14:27

    Depends on your definition of whole number. If you consider only 0 and above as whole number then it's as simple as: bool whole = foobar >= 0;.

    0 讨论(0)
  • 2020-12-20 14:32

    All you have to do is define your possible decimal number as an int and it will automatically round it, then compare the double with the int. For example, if your double foobar is equal to 3.5, defining it as an int will round it down to 3.

    double foobar = 3;
    long long int num = foobar;
    
    if (foobar == num) {
      //whole
    } else {
      //not whole
    }
    
    0 讨论(0)
  • 2020-12-20 14:39

    The answer of laurent is great, here is another way you can use without the function floor

    #include <cmath> // fmod
    
    bool isWholeNumber(double num)
    {
      reture std::fmod(num, 1) == 0;
      // if is not a whole number fmod will return something between 0 to 1 (excluded)
    }
    

    fmod function

    0 讨论(0)
  • 2020-12-20 14:42

    A concise version of Pepe's answer

    bool isWhole(double num)
    {
       return num == static_cast<int>(num);
    }
    
    0 讨论(0)
提交回复
热议问题