我有一个计算双数幂的函数,下一个任务是添加选项,以便它可以处理负幂。
所以我将此代码添加到函数中:
if (p < 0)
{
for (y = 1; y <= p; y++)
{
pow *= n;
}
pow = 1/pow;
}
整个程序很短,所以我也将分享它:
#include <stdio.h>
double power(double n, int p); // ANSI prototype
int main(void)
{
double x, xpow;
signed 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); // function call
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, signed int p) // function definition
{
double pow = 1;
int i;
int y;
if (p < 0)
{
for (y = 1; y <= p; y++)
{
pow *= n;
}
pow = 1/pow;
}
for (i = 1; i <= p; i++)
pow *= n;
return pow; // return the value of pow
}
如果我输入输入和我想得到5.0
的功率,我得到......-3
0.008
1