C++编程:用牛顿法做:x 乘以(e的x次方)}—1=0的根

来源:百度知道 编辑:UC知道 时间:2024/05/30 17:27:46

#include<iostream>
#include<cmath>
using namespace std;
double _abs(double x)
{
if(x<0)
return -x;
return x;
}
void main()
{
double x0,x1,e;//x0是初值, e是迭代精度, N是迭代次数
int N,k;
cin>>x0>>e>>N;
for(k=1;k<N;k++)
{
if((1+x0)*exp(x0)==0)
{
cout<<"输入的初值不合理!"<<endl;
break;
}
x1=x0-(x0-exp(-x0))/(1+x0);
if(_abs(x1-x0)<e)
{
cout<<"The result is:"<<x1<<endl;
return;
}
x0=x1;
}
cout<<"迭代失败!"<<endl;
}
例如:
输入 x0=0.5 e=0.0001 N=20