📄 diedai.cpp
字号:
#include<math.h>
#include<iostream.h>
#include<stdio.h>
#define EPS 0.00001
double f( double x)
{
double a=x*x*x;
double b=2*x;
double c=a-b-5;
return c;
}
erfenfa(double a,double b, int c)//二分法
{
double root,ya, yb,yroot;
int i; int acu_c;
ya=f(a);
cout<<ya<<endl;
yb=f(b);
cout<<yb<<endl;
if(ya*yb>0)
{
cout<<"不能求根,条件不满足"<<endl;
}
else{
for(i=1; i<c;i++)
{
root=(a+b)/2; yroot=f(root);
printf("root=%10.6lf\n",root);
if (yroot==0)
{
a=root; b=root;
}
else if (yb*yroot>0)
{
b=root;yb=yroot;
}
else
{
a=root; ya=yroot;
}
if(fabs(b-a)<EPS) break;
}
}
root=(a+b)/2; yroot=f(root);
acu_c=i;
printf("%10.6lf\n",root);
cout<<yroot<<endl;
cout<<"一共迭代了"<<acu_c<<"次"<<endl;
}
double g(double x)
{
return(pow((2.0*x+5.0),1.0/3.0));
}
jiandandiedai(double a, double b, double x0, int c)//简单迭代法
{
// cout<<"ok"<<endl;
int k=1; double x1;
while(k<=c)
{
x1=g(x0);
cout<<x1<<endl;
if((x1<a)||(x1>b))
{
printf("Re-select a proper initial value x0!\n");
}
else
{
if (fabs(x1-x0)<EPS)
{
printf("Method succeed !\n");
printf("root=%10.6lf\n",x1);
break;
}
x0=x1;
k++;
}
}
printf("diedai times=%d\n",k);
if(k>c) printf("Method failed!\n");
}
void aitejin(double a, double b,double x0, int c)//aige jin
{ cout<<"ok"<<endl;
int k=1;
double x1, x2, x3;
while (k<=c)
{
x1=g(x0);
x2=g(x1);
x3=((x0*x2-x1*x1)/(x0-2*x1+x2));
cout<<x3<<endl;
if((x3<a)||(x3>b))
{
printf("Re-select a proper initial value x0!\n");
}
else
{
if(fabs(x3-x0)<EPS)
{
printf("Method succeed !\n");
printf("root=%10.6lf\n",x1);
break;
}
x0=x3;
k++;
}
}
printf("diedai times=%d\n",k);
if(k>c) printf("Method failed!\n");
}
double daoshu(double x)
{
return (3*x*x-2);
}
void newton(double a,double b, double x0,int c)//牛顿迭代法
{
int k=1; double x;
while(k<c)
{
x=x0-f(x0)/daoshu(x0);
cout<<x<<endl;
if((x<a)||(x>b))
{
printf("Re-select a proper initial value x0!\n");
}
else
{
if(fabs(x-x0)<EPS)
{
printf("方法成功 !\n");
printf("root=%10.6lf\n",x);
break;
}
x0=x;
k++;
}
}
printf("diedai times=%d\n",k);
if(k>c) printf("Method failed!\n");
}
void main()
{
double a=2.0 , b=3.0 , x0=(a+b)/2.0; int c=30;
char s='y'; int x=1; int i;
cout<<" "<<"请选择你所需要的求根方法"<<endl;
while(s=='y')
{
cout<<"1:为二分法"<<endl;
cout<<"2:为简单迭代法"<<endl;
cout<<"3:为牛顿迭代法"<<endl;
cout<<"4:埃特金加整收敛法"<<endl;
cout<<endl;
cout<<"请选择"<<endl;
cout<<"请输入你选择的序号:";
cin>>i;
switch(i)
{
case 1:
erfenfa(a,b,c);
break ;
case 2:cout<<"你选择简单迭代法"<<endl;
jiandandiedai(a,b,x0,c);
break;
case 3:
cout<<"你选择的是牛顿迭代法"<<endl;
newton( a, b, 2.5, c);
break;
case 4:
cout<<"你选择的是埃特金加整收敛法"<<endl;
cout<<"ok"<<endl;
aitejin(a,b,x0,c);
break;
case 0:
s='n';
break;
}
if(x==1){
cout<<"要继续吗?(y/n)";
cin>>s;
cout<<endl;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -