4.12趣味百题第六题

发布时间 2023-04-12 20:07:13作者: 混沌武士丞

一 问题描述

     用牛顿迭代法。牛顿迭代法 x=x0-f(x0)/f'(x0),迭代到|x-x0|<=10^-5.

方程 ax*x*x+b*x*x+c*x+d=0; 系数a,b,c,d由主函数输入.求x在1附近的一个根并输出。

二 设计思路

1.设置一个在1附近的x0;

2.利用do-while迭代法求x.

三 流程图

四 伪代码

int x,x0=2

int a,b,c,d

输入a,b,c,d

int t=0;

f=a*x^3+b*x^2+c*x+d

do{ x=x0-|f1(x0)/f2(0)|

if(|x-1|<=10^-5) {t=1,输出x}

}while(t==0)

五 c++代码

#include<iostream>
#include<math.h>
using namespace std;
int a,b,c,d;//系数
int f1(int n){

int f=a*n*n*n+b*n*n+c*n+d;
return f;
}
int f2(int n){

int f=3*a*n*n+2*b*n+c;
return f;
}
int main()
{
int x,x0=2;int t=0;//标志

cout<<"请输入四个常数"<<endl;
cin>>a>>b>>c>>d;
do{
x=x0-fabs(f1(x0)/f2(x0));
if((x-x0)<=fabs(0.00001))
{
t=1;
cout<<x;
}

}while(t==0);


return 0;
}