c++ - 即使表达式为

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

因此,我试图查找给定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)的结果将是两倍。毁了一切。
有两种选择:

  • 在for循环条件中使用x / (int)pow(10, i) != 0。并将结果加1。
    但是请注意floating result of pow() might be corrupted
    如果您没有有充分的理由使用pow(),请坚持第二种选择。
  • 转到下面的for循环。

  • for (; x != 0; x /= 10) {
      power++;
    }
    
    它将原始数字x除以10,直到达到0。

    关于c++ - 即使表达式为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930510/

    相关文章:

    algorithm - 这个嵌套for循环算法的时间复杂度?

    python - Python 3.6 中的循环问题

    c++ - 不可复制的对象和值初始化 : g++ vs msvc

    C++ 返回类型限定符天堂

    c++ - MPI_Bcast 中的段错误

    c++ - 当我使用父类指针将它们添加到 vector 时,我无法使用子类特定函数

    C++ 应用程序在实例化 ofstream 对象时崩溃。

    c++ - 为什么它试图发送一个字符数组而不是一个字符串?

    javascript - 打印出所有重复项 - Javascript - 需要替代解决方案

    c++ - 如何为 operator[] 指定返回类型?