+ 1

Write a program to Calculate power of a number

without including math.h

27th Oct 2016, 9:00 PM
Harimangal Pandey
Harimangal Pandey - avatar
2 ответов
+ 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
28th Oct 2016, 12:37 AM
Zeke Williams
Zeke Williams - avatar
+ 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); }
28th Oct 2016, 9:45 AM
Daniel Oravec
Daniel Oravec - avatar