Reputation: 71
I'm writing a trivial program that doubles the amount of rice grains per each square on a chess board. I'm trying to work out the amount of squares required for at least 1 000 000 000 grains of rice. The problem is, what ever I try, the second if statement gets skipped even though 'test' is false after first iteration.
I've tried an else after the if statement, but the else is skipped when 'test' variable is false.
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";
}
Upvotes: 0
Views: 76
Reputation: 234715
The else
causes the issue. But C++ is more powerful than you can imagine. Rework your loop to
for (
int rice_grains = 1, num_of_squares = 1;
rice_grains <= max_rice_amount;
rice_grains *= 2, ++num_of_squares
){
with
std::cout << "Square " << num_of_squares << " has " << rice_grains << " grains of rice\n";
as the loop body; and weap at the beauty.
Upvotes: 1
Reputation: 11317
Looking at the problem description, this looks a good fit for a while
loop or a do-while
loop.
#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;
}
}
Here you recognize 3 big blocks:
Upvotes: 0