There are two ways to represent n to the power n in C: use the pow function, such as pow(5, 3) to represent 5 raised to the power 3, and the result is 125. Use operator overloading, such as Power(5) ^ 3 represents 5 raised to the third power, and the same result is 125.
In C, n raised to the nth power represents
C. Two methods are provided to express n raised to the nth power. :
1. pow function
<code class="cpp">#include <cmath> double pow(double x, int y);</code>
x
:basey
:exponent Example:
<code class="cpp">#include <iostream> #include <cmath> int main() { double base = 5; int exponent = 3; double result = pow(base, exponent); std::cout << base << " 的 " << exponent << " 次方为 " << result << std::endl; return 0; }</code>
Run result:
<code>5 的 3 次方为 125</code>
2. Operator overloading
You can use operator<<
to overload operators and define your own operators to represent exponentiation operations.
Example:
<code class="cpp">#include <iostream> class Power { public: Power(double base) : base(base) {} double operator^(int exponent) { return pow(base, exponent); } private: double base; }; int main() { Power base(5); double result = base ^ 3; std::cout << 5 << " 的 " << 3 << " 次方为 " << result << std::endl; return 0; }</code>
Run result:
<code>5 的 3 次方为 125</code>
The above is the detailed content of How to express n raised to the nth power in c++. For more information, please follow other related articles on the PHP Chinese website!