简体   繁体   中英

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

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";
else
    cout << "Not whole";

How would I do this?

Assuming foobar is in fact a floating point value, you could round it and compare that to the number itself:

if (floor(foobar) == foobar)
    cout << "It's whole";
else
    cout << "Not whole";

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;

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

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
}

In C++ you can use the following code:

if (foobar - (int)foobar == 0.0 && foobar>=0)
cout << "It's whole";
else
cout << "Not whole";
if (foobar == (int)foobar)
    cout << "It's whole";
else
    cout << "Not whole";

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";

A concise version of Pepe's answer

bool isWhole(double num)
{
   return num == static_cast<int>(num);
}

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; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM