给定两个基数和指数,pow() 函数找到 x 的 y 次方,即 x y。基本上在 C 中,指数值是使用 pow() 函数计算的。pow() 是获取数字幂的函数,但我们必须在 c/c++ 中使用 #include<math.h> 才能使用该 pow() 函数。然后通过两个数字。示例 – pow(4 , 2); 然后我们将得到结果为 4^2,即 16。
示例:
参数:该方法有两个参数:
输出:
输出:
输入: 2.0, 5.0 输出: 32 解释: pow(2.0, 5.0) 执行 2.0 的5次幂,等于 32 输入: 5.0, 2.0 输出: 25 解释: pow(5.0, 2.0) 执行 5.0 的2次幂,等于 25语法:
double pow(double x, double y);
- x :浮点基值
- y :代表多少次幂
// C program to illustrate
// power function
#include <math.h>
#include <stdio.h>
int main()
{
double x = 6.1, y = 4.8;
// Storing the answer in result.
double result = pow(x, y);
printf("%.2lf", result);
return 0;
}
5882.79
pow() 函数与整数的工作
pow() 函数将 'double' 作为参数并返回一个 'double' 值。此函数并不总是适用于整数。一个这样的例子是 pow(5, 2)。当分配给一个整数时,它在某些编译器上输出 24 并且在其他一些编译器上工作正常。但是 pow(5, 2) 没有分配任何整数输出 25。
- 这是因为 5 2(即 25)可能存储为 24.9999999 或 25.0000000001,因为返回类型是 double。当分配给 int 时,25.0000000001 变为 25,但 24.9999999 将给出输出 24。
- 为了克服这个问题并以整数格式输出准确的答案,我们可以将 1e-9 或 0.000000001 添加到结果中并将其类型转换为int例如 (int)(pow(5, 2)+1e-9) 将给出正确的答案( 25,在上面的例子中),与编译器无关。
// C program to illustrate
// working with integers in
// power function
#include <math.h>
#include <stdio.h>
int main()
{
int a;
// Using typecasting for
// integer result
a = (int)(pow(5, 2) + 1e-9);
printf("%d", a);
return 0;
}
25