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

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

下次还敢
Release: 2024-05-01 17:00:55
Original
532 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template