Home >Backend Development >C++ >How to express nth power in c++
Two ways to represent nth power in C: use the standard library function pow(), which receives base and exponent parameters. Customize the ^ operator via operator overloading to calculate the result using a loop.
How to express nth power in C
In C, there are two main ways to express n Power:
1. Standard library function pow()
pow()
The function receives two parameters: The base and exponent, and returns the base raised to the power of the exponent. For example:
<code class="cpp">#include <cmath> int main() { double base = 2; int exponent = 3; double result = pow(base, exponent); // result 为 8 return 0; }</code>
2. Operator overloading
With operator overloading, you can define a custom operator to represent nth power. For example:
<code class="cpp">#include <iostream> class Power { public: double operator()(double base, int exponent) { double result = 1; for (int i = 0; i < exponent; i++) { result *= base; } return result; } }; int main() { Power power; double base = 2; int exponent = 3; double result = power(base, exponent); // result 为 8 std::cout << result << std::endl; return 0; }</code>
When using operator overloading, you can use the ^
operator to represent the nth power, for example:
<code class="cpp">int main() { double base = 2; int exponent = 3; double result = base ^ exponent; // result 为 8 return 0; }</code>
The above is the detailed content of How to express nth power in c++. For more information, please follow other related articles on the PHP Chinese website!