Home  >  Article  >  Backend Development  >  How to express n raised to the nth power in c++

How to express n raised to the nth power in c++

下次还敢
下次还敢Original
2024-05-08 01:51:18464browse

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.

How to express n raised to the nth power in c++

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:base
  • y: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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn