本题比较繁琐,最主要的是输出情况的判断,由于有很多相同的输出部分,因此考虑写成函数直接调用,另外,由于其对输出结果的小数位数有要求,我们还需要事先对其进行一位小数的保留。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a1 = sc.nextDouble();
double b1 = sc.nextDouble();
double a2 = sc.nextDouble();
double b2 = sc.nextDouble();
//加法
printSame(a1, b1, a2, b2, '+');
printResult(myRound(a1 + a2), myRound(b1 + b2));
//减法
printSame(a1, b1, a2, b2, '-');
printResult(myRound(a1 - a2), myRound(b1 - b2));
//乘法
printSame(a1, b1, a2, b2, '*');
printResult(myRound(a1 * a2 - b1 * b2), myRound(a1 * b2 + a2 * b1));
//除法
printSame(a1, b1, a2, b2, '/');
printResult(myRound((a1 * a2 + b1 * b2) / (a2 * a2 + b2 * b2)), myRound((a2 * b1 - a1 * b2) / (a2 * a2 + b2 * b2)));
}
//打印相同的部分
static void printSame(double a1, double b1, double a2, double b2, char c) {
if (b1 < 0 && b2 < 0) {
System.out.printf("(%.1f%.1fi) %c (%.1f%.1fi) = ",a1, b1, c, a2, b2);
} else if (b1 < 0) {
System.out.printf("(%.1f%.1fi) %c (%.1f+%.1fi) = ",a1, b1, c, a2, b2);
} else if (b2 < 0) {
System.out.printf("(%.1f+%.1fi) %c (%.1f%.1fi) = ",a1, b1, c, a2, b2);
} else {
System.out.printf("(%.1f+%.1fi) %c (%.1f+%.1fi) = ",a1, b1, c, a2, b2);
}
}
//打印结果
static void printResult(double a3, double b3) {
if (a3 == 0 && b3 == 0) {
System.out.print(0.0 + "\n");
} else if (a3 == 0) {
System.out.printf("%.1fi\n", b3);
} else if (b3 == 0) {
System.out.printf("%.1f\n", a3);
} else if (b3 < 0) {
System.out.printf("%.1f%.1fi\n", a3, b3);
} else {
System.out.printf("%.1f+%.1fi\n", a3, b3);
}
}
//定义数字的四舍五入,考虑到.1f对第二位数字是四舍五入,有些数字舍之后会变成0被输出,不合要求,需要先进行判断,再进行输出
//不能用自带的round是因为其自动舍入到整数,而其他的函数会返回string类型
static double myRound(double num) {
if (num > 0) {
num = (int) (num * 10 + 0.5) / 10.0;
} else {
num = (int) (num * 10 - 0.5) / 10.0;
}
return num;
}
}