Home  >  Article  >  Backend Development  >  How to express the nth power of a number in C++

How to express the nth power of a number in C++

下次还敢
下次还敢Original
2024-05-01 17:00:55434browse

There are two ways to represent a number raised to the nth power in C: using the pow built-in operator or using the multiplication operator (for integer exponents).

How to express the nth power of a number in C++

Two main ways to represent a number raised to the nth power in C

In C, represents a There are two main ways to raise the nth power of a number:

1. Use the built-in operator

C provides the pow built-in operator, which Accepts two parameters: base and exponent, and returns the base raised to the power of the exponent.

<code class="cpp">#include <cmath>

int main() {
  double base = 2.5;
  int exponent = 3;
  double result = pow(base, exponent);
  std::cout << result << "\n";  // 输出:15.625
  return 0;
}</code>

2. Use multiplication operators

For integer exponents, you can use nested multiplication operators to calculate the nth power of a number. For example, to calculate 2 raised to the third power, you would do the following:

<code class="cpp">int base = 2;
int exponent = 3;
int result = 1;
for (int i = 0; i < exponent; i++) {
  result *= base;
}
std::cout << result << "\n";  // 输出:8</code>

The above is the detailed content of How to express the nth power of a number 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