简体   繁体   中英

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

I want to run an infinite loop which prints the power of the integer 2, namely 2,4,8,16. I have written this code but it is not working correctly in a loop it is giving 0 as answer. However, It works fine without loop means it gives the single answer.

#include <iostream>
using namespace std;

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

Your program does not just output zeroes when I run it. It outputs powers of two for a while, before an overflow causes it to start outputting zeros.

First, add line breaks so you can more easily tell what is happening:

cout << power << endl;

Then try piping the output of your program into less or head -n40 so you can see the beginning of its output:

$ ./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

The problem is that your loop will overflow the maximum int value when repeatedly multiplying by n, which leads to undefined behavior. You need to check your loop to avoid the overflow:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM