Calculate the Power of a Number in C++
Raise a base to an exponent in C++ with pow from <cmath>, using double so fractions and negative powers work. Shows why ^ is XOR and when a plain loop is enough.
1#include <iostream>2#include <cmath>3using namespace std;45int main() {6 double base, exponent, result;78 cout << "Enter base: ";9 cin >> base;1011 cout << "Enter exponent: ";12 cin >> exponent;1314 result = pow(base, exponent);1516 cout << base << " raised to the power " << exponent << " = " << result << endl;1718 return 0;19}
Sample Output
2 raised to the power 8 = 256
pow(2, 8); cout drops the trailing .0.
In this one
- How pow(base, exponent) works
- Why double handles 2.5 and -3 correctly
- Why ^ is not exponent in C++
- When a manual multiply loop is fine
How it works
- 1
Read base (2) and exponent (8) as double.
- 2
Call pow(2, 8) = 256.
- 3
Print the expression and result.
Edge cases
Negative exponent
Enter 2 and -3.
pow returns 0.125. A simple int loop could not do this.
Negative base with a fraction
Enter -8 and 0.5.
The real square root of -8 does not exist, so pow returns NaN, printed as nan or -nan.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does pow(9, 0.5) return?
Pick an answer to check it.
Question 2
What does 3 ^ 2 evaluate to in C++?
Pick an answer to check it.
Questions people ask
Can I write a loop instead?
Yes, for a non-negative whole exponent: result = 1, then multiply by base exponent times.
Why does 10^2 give 8?
^ is bitwise XOR. 1010 XOR 0010 = 1000, which is 8.
Is pow exact for integers?
For small values usually yes, but it works in floating point, so very large results may round.