C程序设计 (第四版) 谭浩强 习题7.13
习题 7.13 用递归方法求n阶勒让德多项式的值,递归公式为:
P n ( x ) = { 1 ( n = 0 ) x ( n = 1 ) ( ( 2 n − 1 ) ⋅ x − P n − 1 ( x ) − ( n − 1 ) ⋅ P n − 2 ( x ) ) / n ( n ≥ 1 ) P_n(x)=\begin{cases}1 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (n = 0)\\x \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (n = 1)\\((2n-1) \cdot x-P_{n-1}(x)-(n-1) \cdot P_{n-2}(x))/n \ \ (n \ge 1) \end{cases} Pn(x)=⎩ ⎨ ⎧1 (n=0)x (n=1)((2n−1)⋅x−Pn−1(x)−(n−1)⋅Pn−2(x))/n (n≥1)
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
#include <stdio.h>
#include <stdlib.h>
double legendrePolynomial(int x, int n){
if(n == 0){
return 1;
}
else if(n == 1){
return x;
}
else{
return ((2*n-1) * x - legendrePolynomial(x, n-1) - (n-1) * legendrePolynomial(x, n-2)) / n;
}
}
int main(){
int x, n;
printf("Enter Legendre Polynomial x, n: ");
scanf("%d %d", &x, &n);
printf("The value of Legendre Polynomial is %.2f\n", legendrePolynomial(x, n));
system("pause");
return 0;
}