我需要检查变量是否是整数,比如我有代码:
double foobar = 3;
//Pseudocode
if (foobar == whole)
cout << "It's whole";
else
cout << "Not whole";
我该怎么做?
答案 0 :(得分:12)
假设foobar
实际上是浮点值,您可以将其舍入并将其与数字本身进行比较:
if (floor(foobar) == foobar)
cout << "It's whole";
else
cout << "Not whole";
答案 1 :(得分:3)
您正在使用int,因此它始终是一个“整数”。但是如果你使用的是双,那么你可以做这样的事情
double foobar = something;
if(foobar == static_cast<int>(foobar))
return true;
else
return false;
答案 2 :(得分:1)
取决于您对整数的定义。如果您只考虑0和以上作为整数,则它就像:bool whole = foobar >= 0;
一样简单。
答案 3 :(得分:1)
劳伦特的答案很棒,这是无需功能层即可使用的另一种方式
#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)
}
答案 4 :(得分:0)
只需撰写function
或expression
即可检查whole number
,并返回bool
。
在通常的定义中我认为整数大于0而没有小数部分。
然后,
if (abs(floor(foobar) )== foobar)
cout << "It's whole";
else
cout << "Not whole";
答案 5 :(得分:0)
您要做的就是将可能的十进制数定义为一个整数,它将自动将其取整,然后将双精度数与该整数进行比较。例如,如果您的双精度foobar
等于3.5
,则将其定义为int会将其四舍五入为3
。
double foobar = 3;
long long int num = foobar;
if (foobar == num) {
//whole
} else {
//not whole
}
答案 6 :(得分:0)
在 C++ 中,您可以使用以下代码:
if (foobar - (int)foobar == 0.0 && foobar>=0)
cout << "It's whole";
else
cout << "Not whole";
答案 7 :(得分:-1)
Pepe答案的简明版本
bool isWhole(double num)
{
return num == static_cast<int>(num);
}