輸出格式: 當(dāng)輸入數(shù)據(jù)非法時(shí),輸出“Wrong Format” 當(dāng)無(wú)實(shí)數(shù)根時(shí),輸出如下字符串“The equation has no roots”; 當(dāng)只有一個(gè)根時(shí),輸出如下格式“The equation has one root: 值”;(注意,輸出的值必須保留四位小數(shù),且值前面有一個(gè)空格) 當(dāng)有兩個(gè)根時(shí),輸入如下格式“The equation has two roots: 值1 and 值2”;(注意,輸出的值必須保留四位小數(shù),且值前面均有一個(gè)空格) 輸入樣例1: 在這里給出一組輸入。例如:
2 6 -554
輸出樣例1: 在這里給出相應(yīng)的輸出。例如:
The equation has two roots: 15.2108 and -18.2108
輸入樣例2: 在這里給出一組輸入。例如:
300.0 0.0 0.00
輸出樣例2: 在這里給出相應(yīng)的輸出。例如:
The equation has one root: 0.0000
import java.util.Scanner;publicclassMain{publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);double[] arr=newdouble[3];int f=1;for(int i =0; i <3; i++){if(sc.hasNextDouble()){arr[i]=sc.nextDouble();}else{f =0;break;}}if(f==1&&arr[0]!=0){//a=0的時(shí)候,不是二次函數(shù),應(yīng)該報(bào)錯(cuò)數(shù)據(jù)不合法double[] roots=newdouble[2];int a=solveQuadratic(arr,roots);if(a==0){System.out.println("The equation has no roots");}elseif(a==1){System.out.printf("The equation has one root: %.4f\n",roots[0]);}elseif(a==2){System.out.printf("The equation has two roots: %.4f and %.4f\n",roots[0],roots[1]);}}else System.out.println("Wrong Format");}publicstaticintsolveQuadratic(double[] eqn,double[] roots){int ret=0;if(eqn[1]*eqn[1]-4*eqn[0]*eqn[2]>=0){roots[0]=(-eqn[1]+Math.sqrt(eqn[1]*eqn[1]-4*eqn[0]*eqn[2]))/(2*eqn[0]);roots[1]=(-eqn[1]-Math.sqrt(eqn[1]*eqn[1]-4*eqn[0]*eqn[2]))/(2*eqn[0]);if(Math.round(roots[0])==Math.round(roots[1])) ret=1;else ret=2;}return ret;}}