递归函数计算hermite(int n, double x),输出保留3位小数

C++函数有一个有趣的特点,即自己可以调用自己(当然main函数除外),此谓递归。
其工作目的是把算法写的比使用非递归函数时更清晰更简洁,而且某些问题,特别是与人工智能有关的问题,更适宜用递归方法。递归的另一个优点是,递归函数不会受到怀疑,较非递归函数而言,某些人更相信递归函数。
递归函数必须定义一个终止条件;否则,函数就会“永远”递归下去,这意味着函数会一直调用自身直到程序栈耗尽,这种“永远”递归下去的现象叫做“无限递归错误”。
一个典型的递归函数模型:
void recurs(formalparamelist)
{
statements1;
if(test)
recurs(realparamelist);
statements2;
}

#include <iostream>
#include <iomanip>
using namespace std;
double hermite(int n, double x);
int main()  
{  
      int a;
      double b;
      double M;
      cin>>a>>b;
      M=hermite(a,b);
      cout<<fixed<<setprecision(3)<<M;
    return 0;  
}
double hermite(int n, double x)  
{  
    if(n<=0)  
    return 1;
    else if(n==1)  
    return 2*x; 
    else 
    return     2*x*hermite(n-1,x)-2*(n-1)*hermite(n-2,x);
}  
发布了102 篇原创文章 · 获赞 93 · 访问量 4956

猜你喜欢

转载自blog.csdn.net/huangziguang/article/details/104785555