即使表达式是,我的 For 循环条件也不起作用

My For Loop condition is not working even when the expression is

所以我试图找到给定 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;
}

首先,您没有将它除以整数。 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。