洛谷oj 1024 一元三次方程(二分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39562952/article/details/82785595

思路:历遍-100~~~100每次递增1,因为题目说每个根起码相隔1;然后如果f(x)*f(x+1)<0说明x到x+1上存在着一个根,然后二分这个区间,需要主要的是,上下界,如果f(l)*f(m)<0说明上届还可以变小,所以r=mid

代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <cstring>
#include <climits>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stdio.h>
#define esp 1e-4
using namespace std;
 /*枚举-100到100之间的数,然后如果找到有可能的两个位置(也就是f(x1)*f(x2)<0)二分(x1----x2)得到最后的答案*/     
double a,b,c,d;
double f(double x)
{
	return a*x*x*x+b*x*x+c*x+d;
} 
double binary(double l,double r)
{
	double mid;
	
	while(r-l>esp)
	{
		mid=(l+r)/2.0;
		
		if(f(mid)*f(l)<0)
		{
			r=mid;
		}
		else
			l=mid;
	}
	return r;
	
	
} 
int main()
{
    while(cin>>a>>b>>c>>d)
    {
    	for(double x=-100;x<=100;x++)
    	{
    		if(f(x)==0)
    		{
    			printf("%.2lf ",x);
			}
    		else if(f(x)*f(x+1)<0)
    		{
    			printf("%.2lf ",binary(x,x+1));
			}
		}
		printf("\n"); 
	}
    /*1  -5  -4  20 */
      
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39562952/article/details/82785595