[英]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;
然后尝试将程序的输出head -n40
到less
或head -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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.