Write a program in c++ to calculate how many squares are required to give the in
ID: 641345 • Letter: W
Question
Write a program in c++ 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. You'll need a loop, of course, and probably an int to keep track of which square you arc at, an int to keep the number of grains on the current square, and an int to keep track of the grains on all previous squares. We suggest that you write out the value of all your variables for each iteration of the loop so that you can see what's going on
Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double grains = 0;
int flag = 0;
for(int i = 0; i < 64; ++i){
grains += pow(2, i);
if(flag == 0 && grains > 1000){
cout << (i + 1) << " squares are required";
cout << " to give the inventor at least 1000 grains of rice" << endl;
flag = 1;
}
if(flag == 1 && grains > 1000000){
cout << (i + 1) << " squares are required";
cout << " to give the inventor at least 1,000,000 grains of rice" << endl;
flag = 2;
}
if(flag == 2 && grains > 1000000000){
cout << (i + 1) << " squares are required";
cout << " to give the inventor at least 1,000,000,000 grains of rice" << endl;
flag = 3;
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.