如何 运行 一个给出正确结果的无限循环? C++

How to run an infinite loop which gives correct result? C++

我想要运行一个打印整数2的幂的无限循环,即2,4,8,16。我已经编写了这段代码,但它在给出 0 作为答案的循环中无法正常工作。但是,它在没有循环的情况下工作正常意味着它给出了单一的答案。

#include <iostream>
using namespace std;

int main()
{
    int n=2,power=1,i=1;
    while(i>0)
    {
    power*=n;
    cout<<power;
    }
    return 0;
}

当我 运行 你的程序不只是输出零。它输出 2 的幂一段时间,然后溢出导致它开始输出零。

首先,添加换行符以便您可以更轻松地判断发生了什么:

cout << power << endl;

然后尝试将程序的输出通过管道传输到 lesshead -n40 以便您可以看到其输出的开头:

$ ./test | head -n40
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
-2147483648
0
0
0
0
0
0
0
0
0

问题是你的循环会在重复乘以 n 时溢出最大 int 值,这会导致未定义的行为。您需要检查循环以避免溢出:

#include <iostream>
#include <limits>

int main()
{
    int n=2,power=1;
    while(power <= std::numeric_limits<int>::max()/n)
    {
        power *= n;
        std::cout << power << ' ';
    }
    std::cout << std::endl;
    return 0;
}