2020-09-02 一元三次方程求解

2020-09-02  本文已影响0人  JalorOo

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;

template<typename DataType>
DataType qmi(DataType m, int k)
{
    DataType res = 1, t = m;
    while (k)
    {
        if (k&1) res = res * t;
        t = t * t;
        k >>= 1;
    }
    return res;
}

int read(){
    int x = 0,f = 1;
    char c = getchar();
    while (c<'0'||c>'9') {
        if (c=='-') {
            f = -1;
        }
        c = getchar();
    }
    while (c>='0'&&c<='9') {
        x = x*10+c-'0';
        c = getchar();
    }
    return x*f;
}

#define fi(a,b) for(int i = a; i <= b; i++)
#define fj(a,b) for(int j = a; j >= b; j--)

double a,b,c,d;

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

int main(){
    cin>>a>>b>>c>>d;
    int cnt = 0;
    for (int i = -100; i< 100; i++) {
        double l = i;
        double r = i+1;
        double x1,x2;
        x1 = func(l);
        x2 = func(r);
        if(!x1){
            printf("%.2lf ",l);
            cnt ++;
        }
        if(x1 * x2 < 0){
            double m;
            while(r - l >= 0.001){//二分控制精度。
                m=(l+r)/2;  //中值
                x1 = func(m);
                x2 = func(r);
                if(x1 * x2 <= 0)
                   l = m;
                else
                   r = m;//计算中点处函数值缩小区间。
            }
            printf("%.2lf ",l);
            cnt ++;
        }
        if(cnt == 3){
            break;
        }
    }
    
    return 0;
}
/*
1 -5 -4 20
============
-2.00 2.00 5.00
*/

上一篇 下一篇

猜你喜欢

热点阅读