我有一个计算双数的幂的函数,下一个任务是添加选项,以便它可以处理负数。
所以我将这段代码添加到函数中:
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
...
答案 0 :(得分:1)
你忘了别的吗?对于if
if (p < 0)
{
for (y = 1; y <= -p; y++)
{
pow *= n;
}
pow = 1/pow;
}
else
for (i = 1; i <= p; i++)
pow *= n;
答案 1 :(得分:0)
如果您输入的电力为-3,那么您的任何条件都不会成立。
if (p < 0)
{
for (y = 1; y <= p; y++)
{
pow *= n;
}
pow = 1/pow;
}
如果p < 0,y永远不会小于p。