![](/img/trans.png)
[英]Check if the input is a whole number in C++ in simple way using isdigit
[英]Is there a way to check if a variable is a whole number? C++
我需要检查一个变量是否是一个整数,假设我有代码:
double foobar = 3;
//Pseudocode
if (foobar == whole)
cout << "It's whole";
else
cout << "Not whole";
我该怎么做?
假设foobar
实际上是一个浮点值,您可以将其四舍五入并将其与数字本身进行比较:
if (floor(foobar) == foobar)
cout << "It's whole";
else
cout << "Not whole";
您使用的是 int 所以它总是一个“整数”。 但是如果你使用的是 double 那么你可以做这样的事情
double foobar = something;
if(foobar == static_cast<int>(foobar))
return true;
else
return false;
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)
}
您所要做的就是将可能的十进制数定义为 int,它会自动舍入它,然后将 double 与 int 进行比较。 例如,如果您的双foobar
等于3.5
,则将其定义为 int 会将其四舍五入为3
。
double foobar = 3;
long long int num = foobar;
if (foobar == num) {
//whole
} else {
//not whole
}
在 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";
只需编写一个function
或expression
来检查whole number
,返回bool
。
在通常的定义中,我认为整数大于 0,没有小数部分。
然后,
if (abs(floor(foobar) )== foobar)
cout << "It's whole";
else
cout << "Not whole";
Pepe 答案的简明版本
bool isWhole(double num)
{
return num == static_cast<int>(num);
}
取决于你对整数的定义。 如果您只将 0 及以上视为整数,那么它很简单: bool whole = foobar >= 0;
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.