编程题:36
import java.util.Scanner;
class Complex {
double real;
double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex add(Complex other) {
return new Complex(real + other.real, imag + other.imag);
}
public Complex sub(Complex other) {
return new Complex(real - other.real, imag - other.imag);
}
public Complex mul(Complex other) {
double r = real * other.real - imag * other.imag;
double i = real * other.imag + imag * other.real;
return new Complex(r, i);
}
public Complex div(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
double r = (real * other.real + imag * other.imag) / denominator;
double i = (imag * other.real - real * other.imag) / denominator;
return new Complex(r, i);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (Math.abs(real) < 1e-9 && Math.abs(imag) < 1e-9) {
return "0.0";
}
if (Math.abs(real) >= 1e-9) {
sb.append(String.format("%.1f", real));
}
if (imag > 1e-9) {
sb.append("+").append(String.format("%.1f", imag)).append("i");
} else if (imag < -1e-9) {
sb.append(String.format("%.1f", imag)).append("i");
}
String res = sb.toString();
if (res.endsWith(".0i")) {
res = res.replace(".0i", "i");
}
if (res.startsWith("+")) {
res = res.substring(1);
}
return res;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a1 = scanner.nextDouble();
double b1 = scanner.nextDouble();
double a2 = scanner.nextDouble();
double b2 = scanner.nextDouble();
Complex c1 = new Complex(a1, b1);
Complex c2 = new Complex(a2, b2);
System.out.println("(" + formatComplex(c1) + ") + (" + formatComplex(c2) + ") = " + c1.add(c2));
System.out.println("(" + formatComplex(c1) + ") - (" + formatComplex(c2) + ") = " + c1.sub(c2));
System.out.println("(" + formatComplex(c1) + ") * (" + formatComplex(c2) + ") = " + c1.mul(c2));
System.out.println("(" + formatComplex(c1) + ") / (" + formatComplex(c2) + ") = " + c1.div(c2));
}
public static String formatComplex(Complex c) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%.1f", c.real));
if (c.imag >= 0) {
sb.append("+");
}
sb.append(String.format("%.1f", c.imag)).append("i");
String s = sb.toString();
if (s.endsWith(".0i")) {
s = s.replace(".0i", "i");
}
return s;
}
}
浙公网安备 33010602011771号