Calculate the Power of a Number in C++
base^exponent in C++ with pow. 2^8 is 256. ^ is XOR, not power.
BeginnerLoop ProgramsExample 12 of 14
calculate-the-power-of-a-number.cpp
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}
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.