我正在编写一个简单的程序,使棋盘上每个方格的米粒数量增加一倍。我正在尝试计算至少 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/