for循环中的条件未执行

时间:2019-04-27 15:33:34

标签: c++ loops for-loop

我正在编写一个微不足道的程序,将棋盘上每个正方形的米粒数量加倍。我正在尝试计算至少1000000粒米所需的平方数。问题是,无论我尝试什么,即使第一次迭代后'test'为假,第二个if语句也会被跳过。

我在if语句之后尝试过else,但是当'test'变量为false时,else会被跳过。

    constexpr int max_rice_amount = 1000000000;  
    int num_of_squares = 0;
    int rice_grains = 0;
    bool test = true; // so we can set rice_grains amount to 1

    for (int i = 0; i <= max_rice_amount; i++)
    {
        if (test == true)
        {
            rice_grains = 1;  // This will only happen once
            test = false;
        }
        else if (test == false)
            rice_grains *= 2;

        ++num_of_squares;
        std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";

    }

2 个答案:

答案 0 :(得分:1)

else导致了问题。但是C ++的功能比您想象的要强大。将循环重做为

for (
    int rice_grains = 1, num_of_squares = 1;
    rice_grains <= max_rice_amount;
    rice_grains *= 2, ++num_of_squares
){

使用

 std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";

作为循环体;并为美丽而哭泣。

答案 1 :(得分:0)

查看问题描述,这看起来很适合while循环或do-while循环。

#include <iostream>

void f()
{
    constexpr int max_rice_amount = 1000000000;  

    int num_of_squares = 1;
    int rice_grains = 1;

    while (rice_grains < max_rice_amount)
    {
        std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";
        rice_grains *= 2;
        ++num_of_squares;
    }
}

Code at compiler explorer

在这里您可以识别3个大块:

  • 初始化
  • 一段时间内的“直到”状态
  • 操纵