1.在1附近找任一实数作为x0的初值,取1.5,x0 = 1.5;
2.分别计算f(x),f'(x)的值
3.令h = f(x)/f'(x);
4.x = x0 - h;令x0 = x准备进行下一次循环;
5.若|x-x0| >= 1e-5,则继续进行循环,反之输出x的值;
#include<iostream>
#include<cmath>
using namespace std;
float solution(float a, float b, float c, float d);
int main()
{
float a, b, c, d, x;
cout << "请输入方程的系数:" << endl;
cin >> a >> b >> c >> d;
x = solution(a, b, c, d);
cout<<"所求方程的根为:" << x << endl;
return 0;
}
float solution(float a, float b, float c, float d)
{
float x0, x = 1.5, f, fd, h;
do
{
x0 = x;
f = a * x0 * x0 * x0 + b * x0 * x0 + c * x0 + d;
fd = 3 * a * x0 * x0 + 2 * b * x0 + c;
h = f / fd;
x = x0 - h;
} while (fabs(x - x0) >= 1e-5);
return x;
}