简体   繁体   English

有没有办法检查变量是否是整数? C++

[英]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:假设foobar实际上是一个浮点值,您可以将其四舍五入并将其与数字本身进行比较:

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

You are using int so it will always be a "whole" number.您使用的是 int 所以它总是一个“整数”。 But in case you are using a double then you can do something like this但是如果你使用的是 double 那么你可以做这样的事情

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 laurent 的回答很棒,这里有另一种无需功能层即可使用的方法

#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 fmod 函数

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.您所要做的就是将可能的十进制数定义为 int,它会自动舍入它,然后将 double 与 int 进行比较。 For example, if your double foobar is equal to 3.5 , defining it as an int will round it down to 3 .例如,如果您的双foobar等于3.5 ,则将其定义为 int 会将其四舍五入为3

double foobar = 3;
long long int num = foobar;

if (foobar == num) {
  //whole
} else {
  //not whole
}

In C++ you can use the following code:在 C++ 中,您可以使用以下代码:

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 .只需编写一个functionexpression来检查whole number ,返回bool

in usual definition i think whole number is greater than 0 with no decimal part.在通常的定义中,我认为整数大于 0,没有小数部分。

then,然后,

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

A concise version of Pepe's answer Pepe 答案的简明版本

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;如果您只将 0 及以上视为整数,那么它很简单: bool whole = foobar >= 0; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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