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(); } }
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/15407618.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
JAVA习题
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步