本文實(shí)例講述了C++使用遞歸方法求n階勒讓德多項(xiàng)式的實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
/** 作 者: 劉同賓* 完成日期:2012 年 11 月 24 日* 版 本 號(hào):v1.0* 輸入描述:* 問(wèn)題描述: 用遞歸方法求n階勒讓德多項(xiàng)式的值。。* 程序輸出:* 問(wèn)題分析:略* 算法設(shè)計(jì):略*/#include<iostream>using namespace std;int main(){ double p(double,double); double s,n,x; cout<<"請(qǐng)輸入n與x的值:"; cin>>n>>x; s=p(n,x); cout<<"則多項(xiàng)式的值為:"<<s<<endl; return 0;}double p(double n,double x){ double s; // 函數(shù)名與變量名不能相同。 if(n==0) { s=1; } else if(n==1) { s=x; } else { s=((2*n-1)*x-p((n-1),x)-(n-1)*p((n-2),x))/n;//遞歸。上機(jī)指導(dǎo)上寫的是s=((2*n-1)*x*p((n-1),x)-(n-1)*p((n-2),x))/n 當(dāng)輸入3 4時(shí),結(jié)果是154 } return s;}
希望本文所述對(duì)大家C++程序設(shè)計(jì)有所幫助。