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

思路:历遍-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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值