实验题目 用递归与非递归方式求Hermite多项式的值 实验日期 2013年6月16日 一、 实验目的
本实验的目的是进一步理解递归设计与调用,理解函数递归调用的执行过程,比较递归与非递归方法,从中体会递归的优点。 二、实验问题描述
Hermite本身就是通过递归定义的,当n等于0或1时,问题的答案可以直接计算得到;当n>1时,当前问题的答案Hn(x)需要Hn-1(x)和Hn-2(x)的结果才能算出。
三、实验问题问题
递归是程序调用自身的编程,一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,他通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大减少了程序的代码量。
四、实验结果(程序)及分析
//ex5_17.cpp:编写输出Hermite多项式对应变量x的前n项值得递归函数
#include
float P(int,float); //函数原型 int main()
{ int n; float x;
cout<<\ cin>>n>>x;
cout<<\ cout<
float P(int n,float x) //定义名为P的函数{
if(n==0)
return(1); //求n=0时的值 else if(n==1)
return(2*x); //求n=2时的值 else
return(2*x*P(n-1,x)-2*(n-1)*P(n-2,x)); //时,得Hn(x)的值
}
测试数据与输出
Please enter n and x: 2 ,1 P(2,1)=2
当n>1 Please any key to continue 调试过程中出现的问题以及解决策试:
C:\\Users\\Administrator\\Desktop\\
新
建
文
件
夹
(4)\\Cpp1.cpp(21) : error C2143: syntax error : missing ')' before ';'
执行 cl.exe 时出错.
Cpp1.obj - 1 error(s), 0 warning(s) 解决:return后面应是完整括号;
//ex5_17.cpp:编写输出Hermite多项式对应变量x的前n项值的非递归函数
#include
float x;int n;float a;
cout<<\ cin>>x>>n; a=P(x,n);
cout<
float P(float x,int n) {
if(n==0) return(1); if(n==1) return(2*x); float h1=1,h2=2*x,h3; for(int i=2;i<=n;i++) {
h3=2*x*h2-2*(i-1)*h1; h1=h2;h2=h3; }
return h3; }
测试数据与输出 Please enter x and n 1,2,2
Please any key to continue 调试过程中出现的问题以及解决策试: 1,C:\\Users\\Administrator\\Desktop\\
新
建
文
件
夹
(4)\\Cpp1.cpp(5) : warning C4518: 'int ' : storage-class or type specifier(s) unexpected here; ignored
C:\\Users\\Administrator\\Desktop\\新建文件夹 (4)\\Cpp1.cpp(5) : error C2146: syntax error : missing ';' before identifier
'main'
C:\\Users\\Administrator\\Desktop\\新建文件夹 (4)\\Cpp1.cpp(5) : fatal error C1004: unexpected end of file found 执行 cl.exe 时出错. 解决:函数原型括号后加;。 2,C:\\Users\\Administrator\\Desktop\\
新
建
文
件
夹
(4)\\Cpp1.cpp(25) : warning C4715: 'P' : not all control paths return a value
解决:函数定义要有return h3;