c++ - for循环中的条件不执行

标签 c++ loops for-loop

我正在编写一个简单的程序,使棋盘上每个方格的米粒数量增加一倍。我正在尝试计算至少 1 000 000 000 粒大米所需的正方形数量。问题是,无论我尝试什么,第二个 if 语句都会被跳过,即使在第一次迭代后“test”为 false。

我在 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";

    }

最佳答案

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";

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

关于c++ - for循环中的条件不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882104/

相关文章:

c++ - 默认参数必须在编译时绑定(bind) - 为什么?

c - While 循环未正确迭代

javascript - 通过循环和数组减少 If 语句

for-loop - F# for 循环错误

php - 使用 for 循环帮助将增量值从 jquery 发送到 php 文件

c++ - 尝试编译 C++ 应用程序,找不到头文件

c++ - 在循环中生成随机数_C++ 和循环中的数组 (openmp)

c++ - 删除二维链表数组,如何?

java - for 循环的问题,接收和利用输入

javascript - 如何在 HTML 中的 for 循环中使用文档