跳到主要内容

C++ pow() 函数

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

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

示例

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

int main() {

// 计算 5 的 3 次方
cout << pow(5, 3);

return 0;
}

// 输出:125

pow() 语法

pow() 函数的语法为:

pow(double base, double exponent);

pow() 参数

pow() 函数接受两个参数:

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

pow() 返回值

pow() 函数返回:

  • base^exponent 的结果
  • 如果 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);

// 对于其他参数类型
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;

// 初始化整数参数
int int_base = -4, int_exponent = 6;

double answer;

// 此例中 pow() 返回 double
answer = pow(int_base, int_exponent);

cout << int_base << " ^ " << int_exponent << " = " << answer;

return 0;
}

输出

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