弦截法.cpp

来自「用C++实现的多个算法」· C++ 代码 · 共 33 行

CPP
33
字号
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
double f(double x);
void main()
{
	double x0,x1,x2,e;
	int k=0;
	cout<<"请输入xo、x1和e的值:"<<endl;
	cout<<"初值x0=";
	cin>>x0;
	cout<<"初值x1=";
	cin>>x1;
	cout<<"精度e=";
	cin>>e;
	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<<endl;
		cout<<"x="<<x0<<endl;
		cout<<setw(15)<<setprecision(7)<<" "<<x1<<endl;
	}cout<<"迭代次数为:"<<k<<endl;
}
double f(double x)
{
	double y;
	y=x*x-10;
	return y;
}

⌨️ 快捷键说明

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