# C Primer Plus 第6章 C控制语句：循环 6.11 使用函数返回值的循环的例子

2016/06/04 06:25

``````//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)           //函数定义
{
double pow = 1;
int i;

for (i=1;i<=p;i++)
pow*=n;
return pow;                 //返回pow的值
}

/*下面是一个运行示例：
Enter a number and the positive integer power to which
the number will be raised.Enter q to quit.
1.2 12
1.2 to the power 12 is 8.9161
Enter next pair of numbers or q to quit .
2
16
2 to the power 16 is 65536
Enter next pair of number or q to quit .
q
Hope you enjoyed this power trip --bye!
*/
``````

6.12.1程序讨论

main()程序是一个驱动程序的例子，驱动程序是用来测试一个函数的短小的程序。

double power (doube n,int p);

xpow=power(x,exp);

double power (double n ,int p ) //函数定义

return pow

6.12.2 使用具有返回值的函数

0
2 收藏

0 评论
2 收藏
0