/*1.定义一个求解方程f(x)=0的抽象类solution(这里假设f(x)在区间[a, b]之内单调递增且肯定有唯一的根)。 2.solution的成员数据是区间的下限a,上限b,函数f(x)的名称func_name以及根root; 3.solution的成员函数
时间: 2024-02-16 17:01:02 浏览: 23
包括:构造函数、析构函数、求解函数solve()和显示函数display()。其中,solve()函数应该使用二分法求解方程的根,并将结果保存在root成员变量中;display()函数应该输出解的值。具体实现如下:*/
#include <iostream>
#include <string>
using namespace std;
class solution {
public:
solution(double a, double b, const string& func_name) : a(a), b(b), func_name(func_name) {}
virtual ~solution() {}
virtual void solve() = 0;
virtual void display() const {
cout << "The root of function " << func_name << " in [" << a << ", " << b << "] is: " << root << endl;
}
protected:
double a, b, root;
string func_name;
};
class bisection : public solution {
public:
bisection(double a, double b, const string& func_name) : solution(a, b, func_name) {}
void solve() override {
double fa = f(a), fb = f(b);
if (fa * fb > 0) {
cout << "Error: f(a) and f(b) have same signs!" << endl;
return;
}
const double eps = 1e-6;
while (b - a > eps) {
double mid = (a + b) / 2;
double fmid = f(mid);
if (fmid * fa > 0) {
a = mid;
} else {
b = mid;
}
}
root = (a + b) / 2;
}
private:
double f(double x) const {
// define your function here, e.g.:
// return x * x - 2;
}
};
int main() {
// example usage:
solution* sol = new bisection(-10, 10, "x^2 - 2");
sol->solve();
sol->display();
delete sol;
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)