计算数值的整数次幂的例子:实例程序:
//power.c--计算数值的整数次幂
#include<stdio.h> double power (double n,int p);//函数声明 int main(void) { double x,xpow; int exp; printf("Enter a number and the positive integer power to which\n the number will be raised. Enter q to quit.\n"); while(scanf("%lf %ld",&x,&exp)==2)/*scanf 返回的是正确读入变量的值的个数。 此语句就是输入两个值,前一个是浮点型、后一个是整型,如果都正确输入,则返回2,循环;如果输入错误,返回就不是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\n"); return 0; } double power(double n,int p)//函数定义 { double pow=1; int i; for(i=1;i<=p;i++) pow*=n; return pow; }
运行结果:
对于该句的解释:while(scanf("%lf %ld",&x,&exp)==2) 如:scanf("%d%d", &a, &b); 如果a和b都被成功读入,那么scanf的返回值就是2 如果只有a被成功读入,返回值为1 如果a和b都未被成功读入,返回值为0 如果遇到错误或遇到end of file,返回值为EOF。
时间: 2024-08-27 06:45:37