0

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.

Kla Veg
  • 13
  • 3
  • 1
    Try printing y instead of i – cup May 30 '22 at 11:26
  • 5
    [Is floating point math broken?](https://stackoverflow.com/a/588014/4641116) The `pow` function works on `double` type, and uses logarithms to calculate the answer, which are likely slightly inexact. You've used a hammer to pound in a screw. – Eljay May 30 '22 at 11:29
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Brett Hale May 30 '22 at 11:45
  • This task should be solved [using mathematics first](https://www.wolframalpha.com/input?i=sum+from+i+%3D+0+to+n+of+i%5E2) before starting coding. – Marek R May 30 '22 at 11:45

3 Answers3

0

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;
        
    } 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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;
Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
0

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
PurpleHacker
  • 358
  • 2
  • 9
  • You should mentions that starting from `i=2`, other than a minor speed improvement, is there so a negative number of blocks will output `0` instead of `-1`. Arguably `-1` for a negative number of stones wouldn't be wrong. – Goswin von Brederlow May 30 '22 at 15:25