Search code examples
c++for-looppow

C++ "for" loop with a pow function in it gives incorrect results


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.


Solution

  • 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;