【问题标题】:Is there a way to check if a variable is a whole number? C++有没有办法检查变量是否为整数? C++
【发布时间】:2012-03-25 15:38:07
【问题描述】:

我需要检查一个变量是否为整数,假设我有代码:

double foobar = 3;
//Pseudocode
if (foobar == whole)
    cout << "It's whole";
else
    cout << "Not whole";

我该怎么做?

【问题讨论】:

  • 哎呀抱歉,意思是双重的,刚刚编辑过
  • 我认为你有一个 XY 问题:你有问题 X 和潜在的解决方案 Y,所以你问的是后者,尽管你应该问的是前者。

标签: c++ function variables floating-point


【解决方案1】:

假设foobar 实际上是一个浮点值,您可以将其四舍五入并将其与数字本身进行比较:

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

【讨论】:

  • 整数中没有什么可以向下取整。
【解决方案2】:

您使用的是 int,所以它始终是一个“整数”数字。但如果你使用的是双精度,那么你可以做这样的事情

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

【讨论】:

    【解决方案3】:

    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

    【讨论】:

      【解决方案4】:

      只需写一个functionexpression 来检查whole number,返回bool

      在通常的定义中,我认为整数大于 0,没有小数部分。

      那么,

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

      【讨论】:

      【解决方案5】:

      您所要做的就是将可能的十进制数定义为 int,它会自动对其进行四舍五入,然后将 double 与 int 进行比较。例如,如果您的双精度 foobar 等于 3.5,则将其定义为 int 会将其向下舍入为 3

      double foobar = 3;
      long long int num = foobar;
      
      if (foobar == num) {
        //whole
      } else {
        //not whole
      }
      

      【讨论】:

      • a double 可以表示比 32 位 int 更多的整数,你至少应该使用 long long int
      • 我几乎看不出这有什么关系,@Unlikus,但如果你坚持,我会编辑它。 OP 的示例是 3,所以我认为我需要 long long int
      【解决方案6】:

      在 C++ 中,您可以使用以下代码:

      if (foobar - (int)foobar == 0.0 && foobar>=0)
      cout << "It's whole";
      else
      cout << "Not whole";
      

      【讨论】:

        【解决方案7】:
        if (foobar == (int)foobar)
            cout << "It's whole";
        else
            cout << "Not whole";
        

        【讨论】:

          【解决方案8】:

          取决于您对整数的定义。如果您仅将 0 及以上视为整数,则很简单:bool whole = foobar &gt;= 0;

          【讨论】:

          • @downvoter:整数的定义不准确。参见维基百科:en.wikipedia.org/wiki/Whole_number
          • 呵呵,没听说过。每次出现时,我与之交谈的每个人都同意这个定义。
          【解决方案9】:

          佩佩回答的简明版本

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

          【讨论】:

            猜你喜欢
            • 2020-11-26
            • 2014-01-25
            • 2022-11-12
            • 1970-01-01
            • 2013-07-23
            • 1970-01-01
            • 2017-10-01
            • 2011-02-19
            • 1970-01-01
            相关资源
            最近更新 更多