• 一元三次方程 double输出 -0.00


    求一个 a*x*x*x+b*x*x+c*x+d 的解

    题目很简单,但是我输出了-0.00,然后就一直卡着,这个问题以后要注意。

    让0.00 编程-0.00的方法有很多。

    第一种就是直接特判

    if(fabs(x-0)<eps) x=0;
    

      

    第二种就是+eps,但是这样可能会有问题

    第三种就是二分的时候让答案往正的输出(这个是针对我这个题目的)

    我觉得第三种比较靠谱,所以就写了第三个

    然后就是让这个eps的精度变高一点,这样的话,浮点误差就比较小。

    #include <cstdio>
    #include <iostream>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    #include <queue>
    #include <map>
    #include <stack>
    #define inf 0x3f3f3f3f
    using namespace std;
    const int maxn=2e4+10;
    typedef long long ll;
    const double eps=1e-6;
    double a,b,c,d;
    double cal(double x){
        return a*x*x*x+b*x*x+c*x+d;
    }
    double ok1(double l,double r){
        while(r-l>eps){
            double mid=(l+r)/2;
            if(cal(mid)<0) l=mid;//!!!
            else r=mid; 
        }
        return r;//print r   not l  
    }
    double ok2(double l,double r){
        while(r-l>eps){
            double mid=(l+r)/2;
            if(cal(mid)>0) l=mid;//!!!
            else r=mid; 
        }
        return l;//print l not r 
    }
    int main(){
        scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
        double a1=3*a,b1=2*b,c1=c;
        double x1=(-b1+sqrt(b1*b1-4*a1*c1))/(2*a1);
        double x2=(-b1-sqrt(b1*b1-4*a1*c1))/(2*a1);
        if(x1>x2) swap(x1,x2);
        double ans1=-1,ans2=0,ans3=0;
        if(a>0) ans1=ok1(-100,x1),ans2=ok2(x1,x2),ans3=ok1(x2,100);
        else ans1=ok2(-100,x1),ans2=ok1(x1,x2),ans3=ok2(x2,100);
        printf("%.2f %.2f %.2f
    ",ans1,ans2,ans3);
        return 0;
    }
    //1.000000 134.810000 4749.016919 49980.676731
    //-0.715  -0.71
    
    if(fabs(x-0)<eps) x=0;
  • 相关阅读:
    npm ci fast install All In One
    WebGL & CG All In One
    StackOverflow winterbash 2021 All In One
    jira advanced searching All In One
    localStorage undefined bug All In One
    vcharts bug All In One
    crypto.getRandomValues & Math.random All In One
    Web 3D 技术 All In One
    企业微信如何设置用户当前状态 All In One
    parent.postMessage bug All In One
  • 原文地址:https://www.cnblogs.com/EchoZQN/p/12141881.html
Copyright © 2020-2023  润新知