7-9 一元二次方程(有实根) (10 分)

题目

输入一元二次方程的三个系数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();
   
}
}

posted @ 2021-10-14 17:29  kingwzun  阅读(130)  评论(0编辑  收藏  举报