トピック:
コード交差法を使用して関数の根を見つける一般的な関数を設計します。
この関数には 3 つのパラメータがあります。1 つ目は関数へのポインタで、必要なルートの関数を指します。2 番目と 3 番目のパラメータはルートが位置する間隔を示します。
戻り値は見つかったルートです。
コード:
#include <iostream>
using namespace std;
double f1(double);
double f2(double(*f)(double), double, double); //函数指针
int main()
{
double x1, x2;
cout << "用弦截法求方程y=x*x-x-2的其中一个根" << endl << endl;
cout << "请输入其中一个根所在的大致区间:" << endl;
cout << "请输入左区间x1:";
cin >> x1;
cout << "请输入右区间x2:";
cin >> x2;
cout << endl << "方程y=x*x-x-2的其中一个根为:" << f2(f1, x1, x2) << endl << endl;
system("pause");
return 0;
}
double f1(double x)
{
return x * x - x - 2;
}
double f2(double(*f)(double), double x1, double x2)
{
double y1 = (*f)(x1), y2 = (*f)(x2);
if (y1 == 0) return x1;
if (y2 == 0) return x2;
if (y1 * y2 > 0)
{
cout << endl << "区间输入错误!请重新输入!" << endl << endl;
system("pause");
exit(0);
}
else
{
//两点确定一条直线,求直线与x轴的交点xtmp
double xtmp = x1 + (x1 - x2)*y1 / (y2 - y1);
double ytmp = (*f)(xtmp);
if (ytmp != 0)
{
if (ytmp * y2 < 0) return f2(f1, xtmp, x2);
else return f2(f1, x1, xtmp);
}
else return xtmp;
}
}