【问题标题】:My For Loop condition is not working even when the expression is即使表达式为,我的 For 循环条件也不起作用
【发布时间】:2021-01-03 21:40:09
【问题描述】:

所以我试图找到给定 int 中的位数。我选择查找数字的方法是将给定的 int 除以 10 的幂。由于我将除以整数,因此当 10 提高到足够高的幂时,代码最终会达到 0。会有一个跟踪器跟踪此迭代的每次迭代,并且该跟踪器将能够告诉我有多少数字。

#include <cmath>
#include <iostream>

int findDigits(int x)
{
    //tracks the digits of int
    int power{ 0 };

    for (int i = 0; x / pow(10, i) != 0; i++) //the condition is not working as it should
    {
        //I checked the math expression and it is getting the intended result of zero at i = 3
        int quotient = x / pow(10, i);

        //I then checked the condition and it is becoming false when the expression results in 0
        bool doesWork;
        if (x / pow(10, i) != 0)
            doesWork = true;
        else
            doesWork = false;

        power = i;
    }

    return power;
}

int main()
{
    std::cout << "157 has " << findDigits(157) << " digits";

    return 0;
}

【问题讨论】:

  • 简单得多:不断除以 10,直到结果为 0。
  • 那么问题出在哪里?请描述它(包括预期和实际输出)。

标签: c++ for-loop visual-c++ integer c++17


【解决方案1】:

首先,您不是将其除以整数。 pow() returns double 根据 c++ 参考。因此,x / pow(10, i) 的结果将是两倍。毁了一切。

有两种选择:

  1. 在 for 循环条件中使用 x / (int)pow(10, i) != 0。加上 1 的结果。
    但请注意,floating result of pow() might be corrupted。 如果您正当理由使用pow(),请坚持使用第二个选项。

  2. 改为使用下面的 for 循环。

for (; x != 0; x /= 10) {
  power++;
}

它将原始数x除以10,直到达到0。

【讨论】:

  • 第一个选项不安全。例如,如果pow(10, 1) 返回9.99 会怎样?
  • 不是选角的问题,其实dynamic_cast完全没必要。问题是浮点数学是broken
  • 哦,我明白了,this post 可能会导致问题。我会编辑我的答案。感谢@cigien 的通知。
  • 被设计破坏了,请注意。这种突破是允许大量数字的原因。
  • 另一个技巧是没有多少 10 的幂可以放入一个整数中。您可以创建一个小数组并使用i 作为数组的索引。没有数学。没有循环。
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 2020-04-29
  • 2019-08-09
  • 2023-03-03
  • 2023-03-26
  • 2014-03-30
相关资源
最近更新 更多