+ 1
Write a program to Calculate power of a number
without including math.h
2 Answers
+ 2
double numToThePowerOfN(int num, int n) {
int tempNum = num;
if (n == 1) return num;
else if (n > 0) {
for (int i = 0; i < (n - 1); i++) {
num *= tempNum;
}
return num;
}
else if (n < 0) {
n *= -1;
for (int i = 0; i < (n - 1); i++) {
num *= tempNum;
}
return 1/(double)num;
}
else return 1;
}
cout << numToThePowerOfN(2, 3) << endl;//this is two to the power of 3
+ 1
Actually, you can also use recursion. There are no special cases like decimals, negative numbers etc. to keep it simple to understand.
// Returns a to the power of b
long long power(int a, int b) {
if(b == 0) return 1;
else if(b == 1) return a;
return a * power(a, b - 1);
}