一个递归的简单实现
#include<iostream>using namespace std;#define maxsize 50double p(int n, double x) {struct stack{int no;//保存ndouble val;//保存Pn(x)的值}st[maxsiz...
·
#include<iostream>
using namespace std;
#define maxsize 50
double p(int n, double x) {
struct stack {
int no; //保存n
double val; //保存Pn(x)的值
}st[maxsize];
int top = -1, i;
double fv1 = 1, fv2 = 2 * x;
for (i = n; i >= 2; i--){
top++;
st[top].no = i;
}
while (top >= 0) {
st[top].val = 2 * x * fv2 - 2 * (st[top].no - 1) * fv1;
fv1 = fv2;
fv2 = st[top].val;
top--;
} if (n == 0)
{
return fv1;
}
else {
return fv2; }
}
double p2(int n, double x){
if (n == 0){
return 1;
} else if (n == 1) {
return 2 * x;
} else if (n > 1) {
return 2 * x * p2(n - 1, x) - 2 * (n - 1) * p2(n - 2, x); }
}
int main() {
int n = 5;
double x = 5.00;
double m = p(n, x);
double i = p2(n, x);
cout << "i is : " << i << endl;
cout << "m is : " << m << endl;
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)