问题描述:
计算数值的整数次幂。
分析:
可以使用scanf()来一次读入2个值,如果成功的读入了2个值,scanf()就返回值2,这样您就可以通过
把scanf()的返回值与2进行比较来控制循环。
scanf()函数返回成功读入的项目的个数。如果没有读取任何项目,scanf()会返回值0。
源代码:
#include<stdio.h>
double power(double n,int p);
int main()
{
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 number 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;
for(i = 1;i <= p;i++)
pow *= n;
return pow;
}