C++代码:
```cpp
#include<stdio.h>
#include <iomanip>
#include<iostream>
#include<math.h>
using namespace std;
double a, b, c, d;
double fun(double x)
{
double res = x*(x * (a * x + b) + c) + d;
return res;
}
double daofun(double x)//导数
{
double res = 3*a*x*x + 2 * b * x + c;
return res;
}
double solve(double x)//牛顿迭代
{
double x0;
double x1 = x;
do
{ x0 = x1;
x1 = x0 - fun(x0)/daofun(x0);
}while(fabs(x1 - x0) >= 1e-6);
return x1;
}
int main()
{
cout<<"pls input the parameters of the equation a,b,c,d:"<<endl;
cin>>a>>b>>c>>d;
for(int i = -100; i <= 100; i++)
{
double left = i;
double right = i + 1;//lef和right选择长度为1的区间
if(fun (left ) == 0)
{
cout<<setprecision(6)<<left<<endl;
}
else if(fun(left ) * fun( right) < 0)
{
double jie = solve(right);//迭代的初始点从右端开始
cout<<setprecision(6)<<jie<<endl;
}
}
return 0;
}
```cpp
#include<iostream>
#include<stdio.h>
#include<cmath>//调用了fabs、pow函数
using namespace std;
double f(int,int,int,int,double);//函数声明
double f1(int,int,int,int,double);
double get_solution(int,int,int,int,double);
int main()
{ int a,b,c,d;
double solution,solution_value;
cout<<"pls input the parameters of the equation a,b,c,d;and the estimate x"<<endl;
cin>>a>>b>>c>>d>>solution;
solution_value=get_solution(a,b,c,d,solution);
if(solution_value<=1e-5)//当求得的根很小时,直接让它为0
solution_value=0;
cout<<"the solution near "<<solution<<" is "<<solution_value<<endl;
getchar();
return 0;
}
double f(int w_f,int x_f,int y_f,int z_f,double sol_f)
//当根为x时,用来求f(x)的值
{ double f_result=w_f*pow(sol_f,3)+x_f*pow(sol_f,2)+y_f*sol_f+z_f;
//cout<<"f_result is "<<f_result<<endl; //调试时用
return f_result;
}
double f1(int w_f1,int x_f1,int y_f1,int z_f1,double sol_f1)
//当根为x时,用来求f'(x)的值
{ double f1_result=3*w_f1*pow(sol_f1,2)+2*x_f1*sol_f1+y_f1;
//cout<<"f1_result is "<<f1_result<<endl;//调试时用
return f1_result;
}
double get_solution(int w,int x,int y,int z,double sol)//求根函数,调用了上面两个函数
{ double
value,tmp;
value=sol;
do//使用了x1=x0-f(x0)/f'(x0),不断循环逼近
{tmp=f(w,x,y,z,value);
value=value-tmp/f1(w,x,y,z,value);
//cout<<"funciont_value is "<<tmp<<";value is "<<value<<endl;//调试时用
}
while(fabs(tmp)>=1e-5);//当式子的值与0的绝对值小于1e-5时就认为取到了值
return value;
}
python代码:
# 输入方程的系数
a = int(input('请输入a的值:'))
b = int(input('请输入b的值:'))
c = int(input('请输入c的值:'))
d = int(input('请输入d的值:'))
# 用牛顿迭代法求方程的根
x = 1.5
i = 1 # 随机定义一个i的值,是其能够进入while循环语句
while i >= 1e-5: # (1e-5 = 10**-5)
x0 = x # 用所得的x代替x0原来的值
f = ((a * x0 + b) * x0 + c) * x0 + d # f用来描述方程的值
fd = (3 * a * x0 + 2 * b) * x0 + c # fd用来描述方程求导之后的值
x = x0 - f / fd # 求得更接近方程根的x的值
i = abs(x - x0)
# 输出所求方程的根
print('方程的一个根为:{:7f}'.format(x)) # format的格式化输出,输出保留7位小数的浮点数。