问题:
本题目要求读入一元二次方程3个系数A、B、C,然后输出方程的解。
输入格式:
有多组输入,每组在一行中给出3个绝对值不超过1000的整数A、B、C。
输出格式:
对每一组输入,在一行中输出X值,保留2位小数。若有多个解,用逗号隔开。
输入样例:
在这里给出一组输入。例如:
1 2 1
1 3 2
1 2 3
输出样例:
在这里给出相应的输出。例如:
x=-1.00
x1=-1.00,x2=-2.00
x1=-1.00+1.41i,x2=-1.00-1.41i
以下为我的代码:
import java.util.Scanner;
class Main3 {
/**
* 解题思路
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true){
// 以字符串 coefficient 接收输入数据,Next(); 无法接收空格内容
// 所以要用 nextLine(); 进行接收
String coefficient = sc.nextLine();
// 调用String.parseFloat 方法,用空格截取字符串
// 注意截取时最好用"\\s+",而不是" ",后者只能截取一个空格
String[] arr = coefficient.split(" ");
int a = Integer.parseInt(arr[0]);
int b = Integer.parseInt(arr[1]);
int c = Integer.parseInt(arr[2]);
SolvingEquations(a, b, c);
}
}
public static void SolvingEquations(int a, int b, int c) {
double delta = b * b - 4 * a * c;
double x1, x2;
if (delta == 0) {
x1 = -b / (2 * a);
System.out.println("x=" + String.format("%.2f", x1));
} else if (delta > 0) {
x1 = (-b + Math.sqrt(delta)) / (2 * a);
x2 = (-b - Math.sqrt(delta)) / (2 * a);
System.out.println("x1=" + String.format("%.2f", x1) + ",x2=" + String.format("%.2f", x2));
} else if (delta < 0) {
double real = -b / (2 * a);
double imaginaryPart = Math.sqrt(-delta) / (2 * a);
// x = real + imaginaryPart*i
if (real == 0) {
System.out.println("x1=" + String.format("%.2f", imaginaryPart) + "i" + ",x2=" + "-" + String.format("%.2f", imaginaryPart) + "i");
} else {
System.out.println("x1=" + String.format("%.2f", real) + "+" + String.format("%.2f", imaginaryPart) + "i" + ",x2=" + String.format("%.2f", real) + "-" + String.format("%.2f", imaginaryPart) + "i");
}
}
}
}
测试结果:(正确无误)
提交运行结果: