题目:
8.第6章的程序清单6.20中,power()函数返回⼀个double类型数的正整数次幂。改进该函数,使其能正确计算负幂。另外,函数要处理0的任何次幂都为0,任何数的0次幂都为1(函数应报告0的0次幂未定义,因此把该值处理为1)。要使⽤⼀个循环,并在程序中测试该函数。
9.使⽤递归函数重写编程练习8。
思路:
- 用if...else...条件语句分别处理正整数次幂,负整数次幂和0次幂,8题用for循环语句取值计算;
cpp
//程序清单6.20 power.c程序
// power.c -- 计算数的整数幂
#include <stdio.h>
double power(double n, int p); // ANSI函数原型
int main(void)
{
double x, xpow;
int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2)
{
xpow = power(x, exp); // 函数调⽤
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
// double power(double n, int p) // 原本6.20配套函数定义,只能计算正整数次幂
// {
// double pow = 1;
// int i;
// for (i = 1; i <= p; i++)
// pow *= n;
// return pow; // 返回pow的值
// }
double power(double n, int p)
{
double pow = 1;
int i;
if (p > 0 && n != 0) //计算正整数次幂
{
for (i = 1; i <= p; i++)
pow *= n;
return pow;
}
else if ( p < 0 && n != 0) //计算负整数次幂
{
for (i = 1; i <= (0-p); i++)
pow *= (1.0/n);
return pow;
}
else if (p == 0 && n != 0) //0次幂情况,
{
return 1;
}
else if (p == 0 && n == 0) //0的0次幂情况;
{
printf("The power of 0 to the power of 0 is undefined, so the value is treated as 1\n");
return 1;
}
}
- 9题用递归取代for循环;
cpp
//程序清单6.20 power.c程序
// power.c -- 计算数的整数幂
//8.第6章的程序清单6.20中,power()函数返回⼀个double类型数的正整数次幂。
//改进该函数,使其能正确计算负幂。另外,函数要处理0的任何次幂都为0,任何
// 数的0次幂都为1(函数应报告0的0次幂未定义,因此把该值处理为1)。
//要使⽤⼀个循环,并在程序中测试该函数。
//9.使⽤递归函数重写编程练习8。
#include <stdio.h>
double power(double n, int p); // ANSI函数原型
int main(void)
{
double x, xpow;
int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2)
{
xpow = power(x, exp); // 函数调⽤
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
double power(double n, int p)
{
double pow = 1;
int i;
if (p > 0)
{
pow *= n*power(n, p-1);
return pow;
}
else if ( p < 0 )
{
pow *= (1.0/n)*power(n,p+1);
return pow;
}
else if (p == 0 && n != 0)
{
return 1;
}
else if (p == 0 && n == 0)
{
printf("The power of 0 to the power of 0 is undefined, so the value is treated as 1\n");
return 1;
}
}