当循环终止被覆盖时
While loop termination overriden?
我有一个简单的程序来计算相对于平方的颗粒数:
#include "library/std_lib_facilities.h"
/*There is an old story that the emperor wanted to thank the inventor of the game of chess and asked the inventor to name
his reward. The inventor asked for one grain of rice for the first square, 2 for the second, 4 for the third, and so on,
doubling for each of the 64 squares. That may sound modest, but there wasn’t that much rice in the empire! Write a
program to calculate how many squares are required to give the inventor at least 1000 grains of rice, at least 1,000,000
grains, and at least 1,000,000,000 grains.*/
int main()
{
int grains = 1;
int squares = 1;
while(grains < 1000) {
squares++;
grains *=2;
cout << grains << " rice grains for " << squares << " squares" << 'n';
}
return 0;
}
循环在每个循环后打印颗粒和正方形。这是终端中的输出:
2 rice grains for 2 squares
4 rice grains for 3 squares
8 rice grains for 4 squares
16 rice grains for 5 squares
32 rice grains for 6 squares
64 rice grains for 7 squares
128 rice grains for 8 squares
256 rice grains for 9 squares
512 rice grains for 10 squares
1024 rice grains for 11 squares
如您所见,环路终止大于设置为 grain < 1000
的终止条件。
我对结果没有任何问题,我只想知道为什么循环超过终止标准,为什么它没有停在 512 粒? 是因为循环体中平方的迭代吗?
因为
while(grains < 1000) { //when grain value is 512, which is true.
squares++;
grains *=2; //become 1024
cout << grains << " rice grains for " << squares << " squares" << 'n';
}
相反,您可以将 while 条件更改为while(squares < 10)
或
int grains = 2;
int squares = 2;
while(grains < 1000) { //when grain value is 1024, which is false.
cout << grains << " rice grains for " << squares << " squares" << 'n';
grains *=2;
squares++;
}
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 使用ios:ate写入到流会覆盖现有文件
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 我可以重新分配/覆盖std::字符串吗
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- llvm构建器向基本块添加终止符
- 叮叮当当在修复时插入多个"覆盖"说明符
- 谷歌模拟和覆盖关键字
- 如何使用隔离>终止执行来停止所有线程
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 用于将C++代码转换为 Web 程序集的脚本未终止
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 终止 QProcess 不会终止子进程
- 使用子类覆盖基类中定义的函数
- 当覆盖存在时调用基本虚拟"binded to object"函数
- 当循环终止被覆盖时
- 如何在不终止主应用程序的情况下卸载 ActiveX 的 ocx 以允许覆盖 ocx?