newton.cpp

来自「牛顿法方程求根的经典算法」· C++ 代码 · 共 36 行

CPP
36
字号
//解方程x^2-a=0
#include "math.h"
#include "iostream.h"
#include "stdio.h"
double Fangcheng(double x);
double Daohanshu(double x);
const a=3;
void main()
{
	double x0,x1,e;
	cout<<"输入初值X0:";
	cin>>x0;
	cout<<"输入误差限e:";
	cin>>e;
	x1=x0-Fangcheng(x0)/Daohanshu(x0);
	while(fabs(x1-x0)>=e)
	{
		x0=x1;
		//printf("x=%f",x0);
		x1=x0-Fangcheng(x0)/Daohanshu(x0);
		//printf("=%20.7f",x1);
		cout<<"中间结果为"<<x1<<endl;
     }
	//cout<<x1<<endl;
	printf("%20.7f",x1);
}
double Fangcheng(double x)
{
	return x*x-a;
}
double Daohanshu(double x)
{
	return 2*x;
}

⌨️ 快捷键说明

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