簡體   English   中英

如何運行給出正確結果的無限循環? 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;

然后嘗試將程序的輸出head -n40lesshead -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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM