一、函数的嵌套调用
在调用一个函数的过程中,又调用另一个函数,称为函数的嵌套调用。
C++允许函数多层嵌套调用,只要在函数调用前有函数声明即可。
计算 f(x) = x^3 - 5x^2 + 16x - 80 方程的根,精度e = 1e-6。
#include <iostream>
#include <cmath>
using namespace std;
#define e 1e-10
double f(double x)
{
return ((x-5.0)*x+16.0)*x-80;
}
double root(double x_start, double x_end)
{
double x, f_x_start, f_x, f_x_end;
do{
f_x_start = f(x_start);
f_x_end = f(x_end);
x = (x_start*f_x_end - x_end*f_x_start)/(f_x_end - f_x_start);
f_x = f(x);
if(f_x_start*f_x <= 0)
{
x_end = x;
}
else if(f_x*f_x_end <= 0)
{
x_start = x;
}
// cout << "x = " << x << ", f(x) = " << f_x << endl;
}while(fabs(f_x) > e);
return x;
}
int main()
{
double x_start, x_end, x_root;
do{
cin >> x_start >> x_end;
}while(x_start >= x_end || f(x_start)*f(x_end) >= 0);
x_root = root(x_start, x_end);
cout << "x_start = " << x_start << endl;
cout << "x_end = " << x_end << endl;
cout << "x_root = " << x_root << endl;
return 0;
}
二、函数的递归调用
函数直接或间接调用自己称为递归调用。
汉诺塔问题
#include <iostream>
using namespace std;
int Hanoi(int n, char s, char b, char d, int counter=0)
{
if(n == 1)
{
counter += 1;
cout << counter << ":" << s << "->" << d << endl;
}
else
{
counter = Hanoi(n-1, s, d, b, counter);
counter += 1;
cout << counter << ":" << s << "->" << d << endl;
counter = Hanoi(n-1, b, s, d, counter);
}
return counter;
}
int main()
{
int n;
char a = 'A', b = 'B', c = 'C';
do{
cin >> n;
}while(n<=0);
Hanoi(n, a, b, c);
return 0;
}