Java 复数运算:加减乘除操作实现
本代码使用 Java 实现复数的加、减、乘、除运算。
输入数据以每行表示一个复数表达式,表达式包含多个复数和运算符,按照给定顺序进行运算。
例如,输入:
1 2 1 3 4 4 -5 7 3 -3 2 2 4 6
表示:
(1+2i)+(3+4i)/(-5+7i)*(-3+2i)-(4+6i)
代码包含 Complex 类,用于表示复数,并提供加、减、乘、除等运算方法。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
double real1 = scanner.nextDouble();
double imag1 = scanner.nextDouble();
Complex result = new Complex(real1, imag1);
while (scanner.hasNextInt()) {
int operation = scanner.nextInt();
double real2 = scanner.nextDouble();
double imag2 = scanner.nextDouble();
Complex complex2 = new Complex(real2, imag2);
switch (operation) {
case 1:
result = result.add(complex2);
break;
case 2:
result = result.subtract(complex2);
break;
case 3:
result = result.multiply(complex2);
break;
case 4:
result = result.divide(complex2);
break;
}
}
System.out.printf("%.2f+%.2fi\n", result.getReal(), result.getImag());
}
scanner.close();
}
}
class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public Complex add(Complex other) {
return new Complex(real + other.real, imag + other.imag);
}
public Complex subtract(Complex other) {
return new Complex(real - other.real, imag - other.imag);
}
public Complex multiply(Complex other) {
double realResult = real * other.real - imag * other.imag;
double imagResult = real * other.imag + imag * other.real;
return new Complex(realResult, imagResult);
}
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
if (denominator == 0) {
System.out.println("divided by 0!");
System.exit(0);
}
double realResult = (real * other.real + imag * other.imag) / denominator;
double imagResult = (imag * other.real - real * other.imag) / denominator;
return new Complex(realResult, imagResult);
}
}
代码说明:
- 代码首先使用
Scanner类从标准输入读取数据。 - 每个输入行表示一个复数表达式,前两个数代表第一个复数的实部和虚部。
- 从第三个数开始,每三个数为一组,代表一个运算。第一位数字代表运算类型,1、2、3、4 分别代表加、减、乘、除,后面两个数代表参与运算的复数的实部和虚部。
- 代码使用
Complex类表示复数,并提供add、subtract、multiply、divide方法来实现复数的加、减、乘、除运算。 - 代码按照给定的数据顺序进行运算,不考虑运算的优先级。
- 运算结果以 "(a+bi)" 的形式表示,保留两位小数。如果被 0 除,则显示 "divided by 0!"。
本代码可以帮助理解复数的运算,并提供一个简单的 Java 实现。
原文地址: https://www.cveoy.top/t/topic/nY1k 著作权归作者所有。请勿转载和采集!