简体   繁体   中英

C++ Visual Studio 2012 Express Command window weird behavior

 #include <iostream>
 #include <cmath>
 using namespace std;
 int main()
 {
    int riceamount=2, 
     squarenumber=1,
    totalamount=0,
  neededrice1000=0,
  neededrice1000000=0,
  neededrice1000000000=0;
   cout<<"Amount of rice you need for the square "<< 
   squarenumber<<" is " <<riceamount-1<<endl;

 cout<<"Amount of rice you need for the square "<< 
squarenumber+1<<" is " <<riceamount<<endl;
  squarenumber=2;

 for(int i=2;i<65;i++)

 {

        riceamount=riceamount*2;
        ++squarenumber;
        cout<<"Amount of rice you need for the square "<< squarenumber<<" is " <<riceamount<<endl;
        totalamount=totalamount+ riceamount;
        if (totalamount>1000)
            squarenumber=neededrice1000;
        if (totalamount>10000000 && totalamount<1100000)
            squarenumber=neededrice1000000;
        if (totalamount>1000000000 && totalamount<1100000000)
            squarenumber=neededrice1000000000;
    }  

system("pause");
return 0;}

When I debug Command window print numbers weirdly(after 10 it weirdly turn back to 1 and keep going printing 1 as squarenumber then continue from 2 when c++ gave up calculating powers), as you can see below from image, why? Thanks for any help. Command window picture

Eventually riceamount * 2 overflows the int type.

The behaviour on doing that is undefined , but in your case the computation is effectively modulo a power of 2, which is zero for a large power of 2.

An unsigned long long would be big enough for the total number of grains of rice distributed across 64 squares with 1 grain on the first square.

after 10 it weirdly turn back to 1 and keep going printing 1 as squarenumber

You told it to:

if (totalamount>1000)
    squarenumber=neededrice1000;

This has nothing to do with the Visual Studio command window; it is the stated logic of your program.

I suggest you step through it, line by line, using pencil and paper, so that you understand what you have written.


when c++ gave up calculating powers

It didn't "give up"; you overflowed your int with huge numbers, so your program has undefined behaviour .

For you, this resulted in low values, low enough that the previously pointed-out bug no longer kicks in, and squarenumber is once again free to increment on each iteration.

In this example, a 64-bit type will be enough (so consider uint64_t ).

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