I'm studying coding basics, and had to make a code that calculates how many levels of a pyramid could be built with blocks available "x", if each level is squared (e.g. 1st=1, 2nd=4, 3rd=9 etc.) here's what I have so far, and for the life of me, I can't see where I'm wrong, but the code keeps returning a value of 2 more than it should (e.g. x=25 should result in 3 not 5)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i, x, y=0;
cout<< "How many blocks do you have?"<< endl;
cin>> x;
for (i=1; y<=x; i ) {
y=y pow(i, 2);
} cout<< i <<endl;
return 0;
}
EDIT: Thanks for the answers. copied and tried them out, the for function seems to be the worse option here, so I ended up using while.
CodePudding user response:
It is because your for
loop works even if next layer is impossible to make and then it increments i
once more . That's why your result is bigger by 2 than it should be . Try this:
int tmp;
while(true){
tmp = y i*i;
if(tmp > x) //check if this layer is possible to create
{
i--; //its impossible , so answer is previous i
break;
}
i =1;
y = tmp;
} cout<< i <<endl;
CodePudding user response:
The for loop is incorrect
for (i=1; y<=x; i ) {
y=y pow(i, 2);
}
The result of this expression
y=y pow(i, 2);
can be greater than x but the value of i will be increased.
You could write the for loop for example the following way
int tmp;
for ( i = 0; ( tmp = pow(i 1, 2) ) y <=x; i ) {
y = tmp;
}
CodePudding user response:
This works as well if you want to keep your code pretty much the same way it is already:
int i, x, y=1; // y is now 1
cout<< "How many blocks do you have?"<< endl;
cin>> x;
for (i=2; y<=x; i ) { // i now starts from 2
y=y pow(i, 2);
}
cout<<i-2<<endl; // now i-2