11.3 二分法求方程的根

#include<iostream>
#include<cmath>
#define EPS 1e-6
using namespace std;
double a,b,c,d;

double f(double x)
{
	return x*x*x*a + b*x*x + c*x + d;
}

int main()
{
	cin >> a >> b >> c >> d;
	double mid,y;
	double x1 = 0, x2 = 100;//假设根的范围在0~100之间(f(0)<0,f(100)>0,f函数为单调递增的)
 	mid = x1 + (x2 - x1)/2;
	y = f(mid);
	int time = 1;
	while (fabs(y) > EPS)//一般y=0即为所求结果,这里只需要y的精度在EPS内即可 
	{
		if(y > 0) x2 = mid;
		else x1 = mid;
		mid = x1 + (x2 - x1)/2;
		y = f(mid);
		++ time;
	}
	cout << time << endl;
	printf("%.8f\n", mid);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/82220779