2、设计一个复数类,实现两个复数的加减乘除运算,判断两个复数的值是否相等。Java
时间: 2024-03-27 21:35:57 浏览: 100
C#利用栈实现加减乘除运算
好的,这是一个复数类的示例代码,实现了加减乘除运算和判断两个复数是否相等的功能:
```java
public class ComplexNumber {
private double real; // 复数的实部
private double imaginary; // 复数的虚部
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 加法
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(real + other.real, imaginary + other.imaginary);
}
// 减法
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(real - other.real, imaginary - other.imaginary);
}
// 乘法
public ComplexNumber multiply(ComplexNumber other) {
double newReal = real * other.real - imaginary * other.imaginary;
double newImaginary = real * other.imaginary + imaginary * other.real;
return new ComplexNumber(newReal, newImaginary);
}
// 除法
public ComplexNumber divide(ComplexNumber other) {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double newReal = (real * other.real + imaginary * other.imaginary) / denominator;
double newImaginary = (imaginary * other.real - real * other.imaginary) / denominator;
return new ComplexNumber(newReal, newImaginary);
}
// 判断是否相等
public boolean equals(ComplexNumber other) {
return real == other.real && imaginary == other.imaginary;
}
// toString方法,方便输出
public String toString() {
return real + " + " + imaginary + "i";
}
}
```
使用示例:
```java
ComplexNumber a = new ComplexNumber(1, 2);
ComplexNumber b = new ComplexNumber(3, 4);
ComplexNumber c = a.add(b);
System.out.println(c); // 输出 4.0 + 6.0i
ComplexNumber d = a.subtract(b);
System.out.println(d); // 输出 -2.0 - 2.0i
ComplexNumber e = a.multiply(b);
System.out.println(e); // 输出 -5.0 + 10.0i
ComplexNumber f = a.divide(b);
System.out.println(f); // 输出 0.44 + 0.08i
System.out.println(a.equals(b)); // 输出 false
```
阅读全文