首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当循环终止过度的时候?

问当循环终止过度的时候?
EN

Stack Overflow用户
提问于 2017-03-18 09:04:05
回答 1查看 47关注 0票数 0

我有一个简单的程序来计算与正方形相关的颗粒数:

代码语言:javascript
复制
#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;
}

循环在每个循环之后打印出颗粒和方格。这是终端中的输出:

代码语言:javascript
复制
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粒?是因为循环体中的平方的迭代吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-18 09:06:35

因为

代码语言:javascript
复制
 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(squares < 10)。

或

代码语言:javascript
复制
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++;

        }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42872397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档