Calculate Power of a Number in C++
Calculate Power of a Number in C++ (6 Programs).
BeginnerAdvanced Number ProgramsExample 2 of 13
calculate-power-of-a-number.cpp
1#include <iostream>2#include <cmath>3using namespace std;45int main() {6 double base, exponent;78 cout << "Enter base: ";9 cin >> base;1011 cout << "Enter exponent: ";12 cin >> exponent;1314 // Method 1: Using pow() function15 double result = pow(base, exponent);1617 cout << base << " raised to the power " << exponent << " = " << result << endl;1819 return 0;20}
Output
Enter base: 2 Enter exponent: 8 2 raised to the power 8 = 256
What's going on
This C++ program computes base^exponent with pow from <cmath>. 2^8 is 256.
#include <cmath>
Skip it and pow is an unknown name.
double base, exponent, result;
double so 2.5 and -2 still work. int would truncate 2^(-3).
result = pow(base, exponent);
^ is XOR. 2 ^ 8 is 10, not 256. Don't.
Special cases pow already handles: anything^0 is 1, 2^1 is 2. Fractional exponent 4^0.5 is 2. Negative exponent 2^-3 is 0.125.
A loop result *= base n times only works for a non-negative integer exponent. That's why the library function exists.
Sample: 2 raised to the power 8 = 256.