7-5 sdut-oop-1 简单的复数运算
时间: 2025-03-14 09:00:28 浏览: 48
### Python实现复数运算
以下是基于Python的复数运算实现代码,利用Python内置的`complex`类型来简化复数的操作[^1]:
```python
def complex_operations():
results = []
x_real, x_imaginary = map(int, input().split())
x = complex(x_real, x_imaginary)
while True:
line = input()
if line.strip() == "0 0 0":
break
y_real, y_imaginary, op = line.split()
y = complex(int(y_real), int(y_imaginary))
if int(op) == 1: # 加法
result = x + y
elif int(op) == 2: # 减法
result = x - y
elif int(op) == 3: # 乘法
result = x * y
else:
continue
results.append(result)
for res in results:
print(f"{int(res.real)} {int(res.imag)}"
.replace("j", "").replace("+", ""))
if __name__ == "__main__":
complex_operations()
```
上述代码实现了读取输入并执行复数加减乘操作的功能。通过循环不断接收输入直到遇到终止条件 `0 0 0`。
---
### Java实现复数运算
对于Java中的复数运算,则需要手动定义一个`Complex`类来进行封装[^2]。下面是一个完整的示例代码:
```java
class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}
public Complex multiply(Complex other) {
double r = this.real * other.real - this.imaginary * other.imaginary;
double i = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(r, i);
}
@Override
public String toString() {
return (real != 0 ? real + " " : "") +
(imaginary >= 0 && real != 0 ? "+" : "") +
(imaginary != 0 ? Math.abs(imaginary) + "i" : "");
}
}
public class Main {
public static void main(String[] args) {
java.util.Scanner scanner = new Scanner(System.in);
// 初始化 X
System.out.println("Enter the first complex number:");
double xr = scanner.nextDouble();
double xi = scanner.nextDouble();
Complex x = new Complex(xr, xi);
List<Complex> results = new ArrayList<>();
while (true) {
System.out.println("Enter Y and operation code or '0 0 0' to stop:");
double yr = scanner.nextDouble();
double yi = scanner.nextDouble();
int opCode = scanner.nextInt();
if (yr == 0 && yi == 0 && opCode == 0) {
break;
}
Complex y = new Complex(yr, yi);
switch (opCode) {
case 1 -> results.add(x.add(y));
case 2 -> results.add(x.subtract(y));
case 3 -> results.add(x.multiply(y));
default -> {}
}
}
for (Complex c : results) {
System.out.println(c.toString());
}
}
}
```
此代码创建了一个名为`Complex`的类用于处理复数的相关计算,并提供了加法、减法以及乘法的方法。
---
####
阅读全文
相关推荐
















