C Input of power can be done through the following methods: use the pow(base, exponent) function to directly input the power expression. Use math libraries such as exp and log in the <cmath> header file to perform operations. When the exponent is an integer, it can be calculated efficiently through bit operations.
In C, use the pow(base, exponent)
function to calculate a The power of a number, where base
is the base and exponent
is the exponent.
Directly input a power expression
The most direct way to input a power expression is to use the pow
function:
<code class="cpp">#include <cmath> int main() { double result = pow(2.0, 3.0); // 计算 2 的三次方 std::cout << "结果:" << result << std::endl; return 0; }</code>
Using the math library
Additional options are provided in the <cmath>
header file of the C standard library:
exp
: Calculate the exponent of elog
: Calculate the natural logarithmsqrt
: Calculate the square rootFor example, the following code uses the exp
and log
functions to calculate 2 raised to the third power:
<code class="cpp">#include <cmath> int main() { double result = exp(3.0 * log(2.0)); // e^(3*ln(2)) 等于 2^3 std::cout << "结果:" << result << std::endl; return 0; }</code>
Using bitwise operations
When the exponent is an integer, bit operations can be used for more efficient calculations:
<code class="cpp">int power(int base, int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base; if (exponent < 0) return 1 / power(base, -exponent); int result = 1; while (exponent > 0) { if (exponent % 2 == 1) result *= base; base *= base; exponent /= 2; } return result; } int main() { int result = power(2, 3); // 计算 2 的 3 次方 std::cout << "结果:" << result << std::endl; return 0; }</code>
The above is the detailed content of How to input the middle power in c++. For more information, please follow other related articles on the PHP Chinese website!