Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我的For循环条件即使在表达式为_C++_For Loop_Visual C++_Integer_C++17 - Fatal编程技术网

C++ 我的For循环条件即使在表达式为

C++ 我的For循环条件即使在表达式为,c++,for-loop,visual-c++,integer,c++17,C++,For Loop,Visual C++,Integer,C++17,所以我试图找到给定整数的位数。我选择的方法是将给定整数除以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的幂。因为我将除以整数,所以当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;
}
#包括
#包括
int findDigits(int x)
{
//跟踪int的数字
整数幂{0};
for(inti=0;x/pow(10,i)!=0;i++)//条件没有按它应该的方式工作
{
//我检查了数学表达式,它在I=3时得到了零的预期结果
int商=x/pow(10,i);
//然后我检查了条件,当表达式结果为0时,条件变为false
布尔·多斯沃克;
如果(x/pow(10,i)!=0)
杜斯沃克=真;
其他的
杜斯沃克=假;
功率=i;
}
返回功率;
}
int main()
{

STD::CUT

首先,你不是按照整数来划分的。根据C++引用,X/POW(10,I)的结果是双的。破坏一切。

有两种选择:

  • 在for循环条件内使用
    x/(int)pow(10,i)!=0
    。并将结果加1。
    但是要知道。 如果没有正当理由使用
    pow()
    ,请坚持使用第二个选项

  • 用下面的循环代替

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

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

    简单得多:继续除以10,直到结果为0。那么问题出在哪里?请描述它(包括预期和实际输出)。第一个选项不安全。如果
    pow(10,1)怎么办
    返回
    9.99
    例如?这不是一个施法的问题,事实上,
    dynamic\u cast
    完全没有必要。问题是浮点数学是,哦,我明白了,可能会引起问题。我会编辑我的答案。注意@cigien.breaked by design,提醒你。这个中断是允许大量数字的。另一个技巧一个整数没有很多10的幂。你可以做一个小数组,用
    i
    作为数组的索引。没有数学,没有循环。