天天看點

算法設計- 思維之花方程

Problem E. 思維之花-方程

時間限制 1000 ms

記憶體限制 128 MB

題目描述

有形如:ax3+bx2+cx+d=0 這樣的一個一進制三次方程。給出該方程中各項的系數(a,b,c,d 均為實數),并約定該方程存在三個不同實根(根的範圍在-100至100之間),且根與根之差的絕對值> =1。要求由小到大依次在同一行輸出這三個實根(根與根之間留有空格),并精确到小數點後2位。

  提示:記方程f(x)=0,若存在2個數x1和x2,且x1< x2,f(x1)*(x2)< 0,則在(x1,x2)之間一定有一個根。

輸入資料

輸入該方程中各項的系數 (a , b , c , d 均為實數),

輸出資料

由小到大依次在同一行輸出這三個實根(根與根之間留有空格),并精确到小數點後 2 位。

樣例輸入

1 -5 -4 20

樣例輸出

-2.00 2.00 5.00

// Author     : 農村娃的成長之路
// Time       : 2019/9/25 16:10
// File       : GCDANDLCM.java
// Describe   :  E - 思維之花-方程
// IDE        : IntelliJ IDEA
import java.util.Arrays;
import java.util.Scanner;

public class Equation {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double a = sc.nextDouble();
        double b = sc.nextDouble();
        double c = sc.nextDouble();
        double d = sc.nextDouble();
        double []arr = new double[3];
        int count =0;
        for (double x =-100;x<100;x=x+0.05){
            if (Math.abs(a*x*x*x+b*x*x+c*x+d) <=0.00001){
                if (count<3)
                arr[count++] = x;
            }
        }
        Arrays.sort(arr);
        if(Math.abs(arr[2]-arr[1])>=1&&Math.abs(arr[2]-arr[0])>=1&&
                Math.abs(arr[2]-arr[0])>=1){
            for (int i = 0;i<2;i++){
                System.out.printf("%.2f ",arr[i]);
            }
            System.out.printf("%.2f",arr[2]);
            System.out.println();
        }
    }
}