1. 程式人生 > >C語言迴圈及定義子函式技巧

C語言迴圈及定義子函式技巧

最近在網上看到一段程式碼,感覺很有收穫,他簡化了函式宣告的過程,並且使程式實現部分可迴圈,不用每次都退出重新進

#include<stdio.h>
int main()
{
int ctu=0;
do
{
double Legendre(int,float);
int n;float x;
printf("請輸入n,x:\n");
scanf("%d%f",&n,&x);
if(n<0)
printf("\a請輸入大於等於0的n值");
else
printf("Pn(x)=%lf",Legendre(n,x));
printf("\n輸入1繼續程式,或輸入其他字元以終止\n");
scanf("%d",&ctu);
}while(ctu==1);
return 0;
}

double Legendre(int n,float x)
{
double a;
if(n==0)a=1;
else
if(n==1)a=x;
else
a=((2*n-1)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n;
return (a);
}

 

可以看到,他在進行函式宣告時,double Legendre(int,float);  直接就用int和float來代替變數,只要在編寫子函式那裡寫明名字即可,然後他迴圈也弄得很巧妙