与函数原型:
double power(double x, int n);
应该计算并返回x ^ n的值。表达式power(5.0,4)将评估计算表达式:5.0 * 5.0 * 5.0 * 5.0,计算的结果值是:625.0,将power()函数实现为递归函数。
实现代码
#include
double power(double x, int n);
int main(void)
{
for (double x = 2.0; x <= 5.0; x += 0.5)
{
for (int n = -4; n < 5; ++n)
printf("The value of %.2lf raised to the power %d is %.4lf\n", x, n, power(x, n));
printf("\n");
}
system("pause");
return 0;
}
//计算x的n次幂函数
double power(double x, int n) {
if (n < 0)
{
n = -n;
x = 1.0 / x;
}
if (n == 0)
return 1.0;
return x * power(x, n - 1);
}
执行上面示例代码,得到以下结果:
The value of 2.00 raised to