[英]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;}
当我调试命令窗口打印数字怪异时(在10之后奇怪地转回1并继续打印1作为方形编号然后从2继续当c ++放弃计算能力),如下图所示,为什么? 谢谢你的帮助。 命令窗口图片
最终riceamount * 2
溢出 int
类型。
这样做的行为是未定义的 ,但在你的情况下,计算有效地模2的幂,对于2的大功率,它是零。
unsigned long long
足以使分布在64个方格上的大米粒总数达到第一个方格上的1个粒度。
10之后它奇怪地转回1并继续打印1作为方编号
你告诉它:
if (totalamount>1000)
squarenumber=neededrice1000;
这与Visual Studio命令窗口无关; 这是你的程序的陈述逻辑。
我建议你逐行,使用铅笔和纸,逐步完成它,这样你就能理解你所写的内容。
当c ++放弃计算能力时
它没有“放弃”; 你用大量的数字溢出你的int
,所以你的程序有不确定的行为 。
对于你来说,这导致了低值,足够低以至于先前指出的bug不再开始,并且squarenumber
在每次迭代时再次自由增加。
在这个例子中,64位类型就足够了(所以考虑uint64_t
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.