函数递归
函数的优点与注意:1、可以使结构清晰,方便维护,2、提高代码使用率,任何人都能调用函数。3注意:代码长度一般不超过100行,超过后不易程序维护
递归函数:就是自己调用自己的函数;注意:问题一定要不断缩小;有边界值;有返回段(有返回的过程)
int Age2(int n)
{
if(n==1)
{
return 10;
}
return Age2(n-1)+2;
}
int Sum(int n)//累积求和
{
if(n==0)
{
return 0;
}
return Sum(n-1)+n;
}
int Fac(int n)//求阶乘,时间复杂度:o(n)
{
if(n==0)
{
return 1;
}
return Fac(n-1)*n;
}
int Fibon(int n)//斐波那契数列,不适合递归函数,用递归写得0分,因为时间复杂度太大。
{
if(n==1 || n==2)
{
return 1;
}
return Fibon(n-2)+Fibon(n-1);
①C教材P128.5
用递归方法求n阶勒让德多项式
Pn(x)=
1 n=0
x n=1
((2n-1)x-Pn-1(x)-(n-1)Pn-2(x))/n n>1
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
float LeRangDeDuo(int n,float x);
int main() {
int n;
float x,y;
printf("Input n and x");
scanf("%d%f",&n,&x);
y=LeRangDeDuo(n,x);
printf("The outcome is %float",y);
return 0;
}
float LeRangDeDuo(int n,float x){
if(n==0) return 1;
if(n==1) return x;
if(n>1) return ((2n-1)*x-LeRangDeDuo(n-1,x)-(n-1)*LeRangDeDuo(n-2,x));
}