⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 for_equation_real_radix.cpp

📁 分别用二分法 Newton法 弦截法(割线法) 求方程x3-3x2+x-1= 0的全部实根(精度小于0.00001)。
💻 CPP
字号:
#include<iostream.h>
#include<math.h>
double f(double x)// 定义f(x)函数
{ double yk;
  yk=x*x*x-3*x*x+x-1;
  return yk;
}

double f1(double x)//定义f(x)函数的一级导数
{ double yk;
  yk=3*x*x-6*x+1;
  return yk;
}

void erfen( )//采用二分法求方程的根
{double a=0,b=3;
 double e=0.00001;
 double x,y;
 int k=0;
 y=f(a);
 while(b-a>e)//判断精度
 {x=0.5*(a+b);
  if(y*f(x)<0)b=x;
  else a=x;
  k++;
 }
 cout<<"k="<<k<<endl;
 cout<<"x="<<x<<endl;
 y=f(x);
 cout<<"检查x的函数值是否近似0."<<"y="<<y<<endl;
}
void Newton ( )//采用Newton法求方程的根
{double x0,x,x1;
 double e=0.00001;
 int k=0;
 cout<<"请输入初值x:"<<endl;
 cin>>x;
 x1=x-f(x)/f1(x);
 while(fabs(x1-x)>e)//判断精度
 {x=x1;
  x1=x1-f(x1)/f1(x1);
  k++;
 }
 cout<<"k="<<k<<endl;
 cout<<"x="<<x<<endl;
 x1=f(x);
 cout<<"x1的值是否接近0?"<<"x1="<<x1<<endl;
}
void siantie ( )//采用弦截法求方程的根
{double x0,x1,x2;
 double e=0.00001;
 int k=1;
 cout<<"请输入初值x0:"<<endl;
 cin>>x0;
 cout<<"请输入初值x1:"<<endl;
 cin>>x1;
 x2=x1-f(x1)*(x1-x0)/(f(x1)-f(x0));
 while(fabs(x2-x1)>e)//判断精度
 {x0=x1;
  x1=x2;
  x2=x1-f(x1)*(x1-x0)/(f(x1)-f(x0));
  k++;
 }
 cout<<"k="<<k<<endl;
 cout<<"x2="<<x2<<endl;
}

void main()
{ 
  int k;
  cout<<"*************************************"<<endl;
  cout<<"**********  1: 二分法  **************"<<endl; 
  cout<<"**********  2:Newton法 **************"<<endl;
  cout<<"**********  3:弦截法   **************"<<endl;
  cout<<"**********  0:结束   **************"<<endl;
  cout<<"*************************************"<<endl;
  cout<<endl;
loop: cout<<"请选择其中一个方法求方程的一个实根:"<<endl;
      cin>>k;
      switch(k)
	  { case 0:break;
	    case 1: erfen( ); goto loop;
        case 2: Newton ( ); goto loop;
    	case 3: siantie ( ); goto loop;
		default: {cout<<"输入出错。"<<endl;
			       goto loop;
				 }
		}
  
}
  
  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -