0
#include <iostream>
using namespace std;

int power(int x, int y){
    int z;
    int i;
    for(i = 0; i <= y; ++i){
        z *= x;
    }
    return(z);
}

int main() {
    cout << power(2,2);
    return 0;
}

This is a function that is supposed to calculate the power, however the output is 0 when it is supposed to be 4.

mch
  • 9,424
  • 2
  • 28
  • 42
soup
  • 79
  • 5

2 Answers2

3

You need to set z to some value to begin. You don't.

int z = 1; // or maybe x.
Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
0
# include <iostream>


void power (int x , int y){
int x_0 = x;

for(int z=1; z<y ; z++){
     x*=x_0;
}
std::cout<<x<<std::endl;
}

int main(){
int baseNum =0, exponent =0;

std::cout<<" Enter base number:" <<std::endl;
std::cin>>baseNum;

std::cout<<" Enter exponent :" <<std::endl;
std::cin>>exponent;

power(baseNum, exponent);

}

shpartan
  • 31
  • 6
  • 1
    `pow` is not a good choice for calculating integer powers. It is subject to rounding errors (because it does the calculation in floating point). – Paul Sanders May 22 '21 at 21:12
  • I think that would be the case if you coerced a float or double into an int but not the other way round. – shpartan May 22 '21 at 21:23
  • 1
    `return pow(x,y);` does a `double` to `int` conversion, which truncates the `double`. In certain cases (depending on the exact value returned by `pow`), this returns 1 less than than the correct value. More [here](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Paul Sanders May 22 '21 at 21:29