ep2_14.cpp

来自「这里有大量的c语言习题呢!真的是题海哦」· C++ 代码 · 共 26 行

CPP
26
字号
/* 2.14 用迭代法求方程x*x+10cosx=0的根,误差限为10-5。迭代公式如下:
    x'=(x*x-10*(x*sin(x+cos(x)))/(2*x-10*sin(x))
*/
#include<iostream>
#include<cmath>
using namespace std;

const double e=1e-5;
int main(){
	double x0,x1;
	int n=0;
	cout<<"输入初始近似值:"<<endl;
	cin>>x1;
	do{
		x0=x1;
		x1=(x0*x0-10*(x0*sin(x0)+cos(x0)))/(2*x0-10*sin(x0));
			//x0是上次算出的结果,x1用作保存新算出的结果
		n++;
	} while ((fabs(x1-x0) >e)&&(n<=1e5));
	if(n>1e5)
		cout<<"超出迭代1e5次\n";
	else cout<<"方程x*x+10*cos(x)=0的一个根为:"<<x1<<endl;
	cout<<"方程误差为:"<<x1*x1+10*cos(x1)<<endl;
	return 0;
}

⌨️ 快捷键说明

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