Home > Backend Development > C++ > How to input the middle power in c++

How to input the middle power in c++

下次还敢
Release: 2024-05-01 10:30:30
Original
1069 people have browsed it

C Input of power can be done through the following methods: use the pow(base, exponent) function to directly input the power expression. Use math libraries such as exp and log in the <cmath> header file to perform operations. When the exponent is an integer, it can be calculated efficiently through bit operations.

How to input the middle power in c++

Input of the power of C

In C, use the pow(base, exponent) function to calculate a The power of a number, where base is the base and exponent is the exponent.

Directly input a power expression

The most direct way to input a power expression is to use the pow function:

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

int main() {
  double result = pow(2.0, 3.0); // 计算 2 的三次方
  std::cout << "结果:" << result << std::endl;
  return 0;
}</code>
Copy after login

Using the math library

Additional options are provided in the <cmath> header file of the C standard library:

  • exp: Calculate the exponent of e
  • log: Calculate the natural logarithm
  • sqrt: Calculate the square root

For example, the following code uses the exp and log functions to calculate 2 raised to the third power:

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

int main() {
  double result = exp(3.0 * log(2.0)); // e^(3*ln(2)) 等于 2^3
  std::cout << "结果:" << result << std::endl;
  return 0;
}</code>
Copy after login

Using bitwise operations

When the exponent is an integer, bit operations can be used for more efficient calculations:

<code class="cpp">int power(int base, int exponent) {
  if (exponent == 0) return 1;
  if (exponent == 1) return base;
  if (exponent < 0) return 1 / power(base, -exponent);

  int result = 1;
  while (exponent > 0) {
    if (exponent % 2 == 1) result *= base;
    base *= base;
    exponent /= 2;
  }
  return result;
}

int main() {
  int result = power(2, 3); // 计算 2 的 3 次方
  std::cout << "结果:" << result << std::endl;
  return 0;
}</code>
Copy after login

The above is the detailed content of How to input the middle power in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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