P1024 一元三次方程求解

https://www.luogu.com.cn/problem/P1024

方法一:暴力枚举

#include<bits/stdc++.h>
using namespace std;
double a, b, c, d, fx;
int main()
{
	cin>>a>>b>>c>>d;
	for(int i=-1000000; i<=1000000; i++){//根据数值范围放大,获得精度 
		double x=1.0*i/10000;//同比例缩小 
		fx=a*x*x*x+b*x*x+c*x+d;//函数值 
          //注意此处实数的精度比较,第一提交我写得是fx==0结果只得了50分 if(abs(fx-0.0)<1e-6)cout<<fixed<<setprecision(2)<<x<<" ";//符合答案输出
           } return 0; }

 方法二:二分答案

#include<bits/stdc++.h>
using namespace std;
double a, b, c, d, fx;
double f(double x){
	return a*x*x*x+b*x*x+c*x+d;
}
double binaryseach(double l, double r){
	
	
	while(l+1e-6<=r){//注意实数类型比较的精度控制
		
		double mid=(r+l)/2;
		
		if(f(mid)==0)return mid;
		
		if(f(mid)*f(l)<0)r=mid;
		else if(f(mid)*f(r)<0) l=mid;
	} 
	return l;
	
}
int main()
{
	cin>>a>>b>>c>>d;
	for(double i=-100; i<100; i++){
		//注意此处分两种情况讨论 
		if(f(i)*f(i+1.0)<0)
			cout<<fixed<<setprecision(2)<<binaryseach(i,i+1.0)<<" ";
		else if(f(i)==0)
			cout<<fixed<<setprecision(2)<<i<<" ";
	}
	
	return 0;
 } 

 同类型题练习:http://ybt.ssoier.cn:8088/problem_show.php?pid=1241

题解:

#include<bits/stdc++.h>
using namespace std;
double f(double x){
	return x*x*x*x*x-15*x*x*x*x+85*x*x*x-225*x*x+274*x-121;
}

int main()
{
	double l=1.5, r=2.4;
	double ans;
	bool b=0;            //为了标记答案是否已经出现
	while(l+1e-8<=r){    //注意实数类型比较的精度控制
		double mid=(l+r)/2;
		if(f(mid)==0){
			ans=mid;
			b=1;
			break;
		}
		if(f(mid)<0)r=mid;
		if(f(mid)>0)l=mid;
	}
	if(!b)ans=r;        //答案没有出现,就求出近似值
	printf("%.6lf",ans);
	return 0;
}

 

posted @ 2020-06-27 15:21  TFLSNOI  阅读(234)  评论(0编辑  收藏  举报