//弦截法求解方程的根 //要求:输入左右两个端点x值 //结果:在一定精度范围内求解出方程的根 //难点:1)推导出x处的横坐标的求解公式 2)迭代掉原来的左端点或者右端点 #include "pch.h" #include <iostream> #include <cmath> #include <iomanip> using namespace std; double f(double x); double xpoint(double x1, double x2); double root(double x1, double x2); int main() { double x1, x2, f1, f2, x; do { cout << "input x1,x2:"; cin >> x1 >> x2; f1 = f(x1); f2 = f(x2); } while (f1*f2>=0); x = root(x1, x2); cout << setiosflags(ios::fixed) << setprecision(7); cout << "A root of equation is " << x << endl; return 0; } double f(double x) { double y; y = x * x*x - 5 * x * x + 16 * x - 80; return y; } double xpoint(double x1, double x2) { double x; x = (x1*f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); return x; } double root(double x1,double x2) { double x, y, y1; y1 = f(x1); do { x = xpoint(x1, x2); y = f(x); if (y*y1 > 0) { y1 = y; //细节:如果同号,需要替代掉左端点原来的y1值和x1值, x1 = x; //y1值用于与求解出来的y值相乘以判断需要保留左端点还是右端点 } else x2 = x; } while (fabs(y)>=0.00001); //fabs 双精度求绝对值函数,包含于cmath库,因而需要包含cmath头文件 return x; }
原文地址:https://www.cnblogs.com/BoltLi/p/10307000.html
时间: 2024-11-09 15:13:53