7-9 一元二次方程(有實根) (10 分)
阿新 • • 發佈:2021-10-14
題目
輸入一元二次方程的三個係數a、b、c的值,輸出其兩個根(假設方程有實根)。要求大根先輸出,小根後輸出。
正確程式碼
import java.util.Scanner; class Main { 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 dt = b * b - 4.0 * a * c; if(dt>0) { double x1 = (-b + Math.sqrt(dt)) / (2.0 * a); double x2 = (-b - Math.sqrt(dt)) / (2.0 * a); double ans1 = (double) (Math.round(x1 * 1000)) / 1000; double ans2 = (double) (Math.round(x2 * 1000)) / 1000; System.out.printf("X1=%.3f\n", ans1); System.out.printf("X2=%.3f", ans2); } else { double x1 = (-b + Math.sqrt(dt)) / (2.0 * a); double ans1 = (double) (Math.round(x1 * 1000)) / 1000; System.out.printf("X1=%.3f\n", ans1); System.out.printf("X1=%.3f\n", ans1); } sc.close(); } }
錯誤程式碼
錯誤原因,沒有判斷double dt = b * b - 4.0 * a * c;
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); double a=sc.nextDouble(); double b=sc.nextDouble(); int c=sc.nextInt(); if(a!=0) { double dt=b*b-4.0*a*c; double x1=(-b+Math.sqrt(dt))/(2.0*a); double x2=(-b-Math.sqrt(dt))/(2.0*a); double ans1=(double )(Math.round(x1*1000))/1000; double ans2=(double)(Math.round(x2*1000))/1000; System.out.printf("X1=%.3f\n",ans1); System.out.printf("X2=%.3f",ans2); } else { double ans1=-c/b; double ans2=ans1; System.out.printf("X1=%.3f\n",ans1); System.out.printf("X2=%.3f",ans2); } sc.close(); } }