基础篇课后习题答案,做了大部分,虽然不一定是最佳代码,但是保证每个都能运行,如有更好的答案,欢迎讨论
3.1 解一元二次方程
double a, b, c, r1, r2;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入a:");
a = scanner.nextDouble();
System.out.print("请输入b:");
b = scanner.nextDouble();
System.out.print("请输入c:");
c = scanner.nextDouble();
if (Math.pow(b, 2) - (4 * a * c) > 0) {
r1 = (-b + Math.pow((Math.pow(b, 2) - (4 * a * c)), 0.5)) / 2 * a;
r2 = (-b - Math.pow((Math.pow(b, 2) - (4 * a * c)), 0.5)) / 2 * a;
System.out.print("方程式的两个根为:" + (double) Math.round(r1 * 1000) / 1000 + "和" +
(double) Math.round(r2 * 1000) / 1000);
} else if (Math.pow(b, 2) - (4 * a * c) == 0) {
r1 = (-b + Math.pow((Math.pow(b, 2) - (4 * a * c)), 0.5)) / 2 * a;
System.out.print("方程式只有一个根:" + (double) Math.round(r1 * 1000) / 1000);
} else {
System.out.print("该方程式无实数根");
}
3.3 解2乘2线性方程
double a, b, c, d, e, f, x, y;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入a:");
a = scanner.nextDouble();
System.out.print("请输入b:");
b = scanner.nextDouble();
System.out.print("请输入c:");
c = scanner.nextDouble();
System.out.print("请输入d:");
d = scanner.nextDouble();
System.out.print("请输入e:");
e = scanner.nextDouble();
System.out.print("请输入f:");
f = scanner.nextDouble();
if ((a * d) - (b * c) == 0) {
System.out.print("方程式无解");
} else {
x = ((e * d) - (b * f)) / ((a * d) - (b * c));
y = ((a * f) - (e * c)) / ((a * d) - (b * c));
System.out.println("x 为:" + x);
System.out.print("y 为:" + y);
}
3.4 随机月份
<