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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9612839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:04:23  来源:igfitidea点击:

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

c++functionvariablesfloating-point

提问by Billjk

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?

我该怎么做?

回答by laurent

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

回答by Pepe

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

您使用的是 int 所以它总是一个“整数”。但是如果你使用的是 double 那么你可以做这样的事情

double foobar = something;
if(foobar == static_cast<int>(foobar))
   return true;
else
   return false;

回答by Asha

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;

回答by Rohit Vipin Mathews

just write a functionor expressionto Check for whole number, returning bool.

只需写一个functionorexpression到 Check for 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";

回答by Moia

A concise version of Pepe's answer

Pepe 答案的简明版本

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