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,则返回类型Promoted
是long double
- 否则,返回类型
Promoted
是double
示例 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
另请阅读