使用函數返回值的循環例子
阿新 • • 發佈:2017-08-01
c
計算數值的整數次冪的例子:實例程序:
//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。
使用函數返回值的循環例子