C++ pow()

pow() 函数返回第一个参数的第二个参数次幂的结果。此函数在 cmath 头文件中定义。

在 C++ 中,pow(a, b) = ab

示例

#include <iostream>
#include <cmath>
using namespace std;

int main() {

// computes 5 raised to the power 3 cout << pow(5, 3);
return 0; } // Output: 125

pow() 语法

pow() 函数的语法是

pow(double base, double exponent);

pow() 参数

pow() 函数接受两个参数

  • base - 基值
  • exponent - 基数的指数

pow() 返回值

pow() 函数返回

  • baseexponent 的结果
  • 如果 exponent 为零,则返回 1.0
  • 如果 base 为零,则返回 0.0

pow() 原型

cmath 头文件中定义的 pow() 的原型是

double pow(double base, double exponent);

float pow(float base, float exponent);

long double pow(long double base, long double exponent);

// for other argument types
Promoted pow(Type1 base, Type2 exponent);

C++ 11 起,

  • 如果传递给 pow() 的任何参数是 long double,则返回类型 Promotedlong double
  • 否则,返回类型 Promoteddouble

示例 1: C++ pow()

#include <iostream>
#include <cmath>
using namespace std;

int main () {
  double base, exponent, result;
	
  base = 3.4;
  exponent = 4.4;

result = pow(base, exponent);
cout << base << " ^ " << exponent << " = " << result; return 0; }

输出

3.4 ^ 4.4 = 218.025

示例 2: 不同参数的 pow()

#include <iostream>
#include <cmath>
using namespace std;

int main () {
  long double base = 4.4, result;
  int exponent = -3;

result = pow(base, exponent);
cout << base << " ^ " << exponent << " = " << result << endl; // initialize int arguments int int_base = -4, int_exponent = 6; double answer;
// pow() returns double in this case answer = pow(int_base, int_exponent);
cout << int_base << " ^ " << int_exponent << " = " << answer; return 0; }

输出

4.4 ^ -3 = 0.0117393
-4 ^ 6 = 4096 

另请阅读

在结束之前,让我们来测试一下您对 C++ cmath pow() 的了解!您能解决以下挑战吗?

挑战

编写一个函数来计算数字的幂。

  • 返回基数的指数次幂。
  • 一个数的幂是通过将基数乘以自身 exponent 次来计算的。
  • 例如,当 base = 2 且 exponent = 3 时,返回值应为 8
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战