I am new to C++ and I wanted to write a programm that calculates the power of any integer using a recursive non-void function. I came up with the following code which did not work and resulted in an error.
#include <iostream>
using namespace std;
int power (int n, int p);
int main() {
int num, pow;
cin >> num >> pow;
cout << power(num, pow);
return 0;
}
int power(int n, int p) {
if(p == 1){
return n;
}else {
return n * power(n, p - 1);
}
}
After some trying around however, I figured out that when I switched p == 1
to p < 2
everything worked totally fine.
I assume there is something going wrong when subtracting 1
from p
, so that 1
and p
have different binary values. I would be so grateful if someone could explain to me why that happens 🙂
user150-0001 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1