簡體   English   中英

有沒有辦法檢查變量是否是整數? C++

[英]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)
}

fmod 函數

您所要做的就是將可能的十進制數定義為 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";

只需編寫一個functionexpression來檢查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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM