用java语言定义复数类complex,实现复数对象相加,相减运算
时间: 2024-09-14 09:05:56 浏览: 47
在Java中,我们可以定义一个名为Complex的类来表示复数,并提供加法和减法的操作。下面是一个简单的例子:
```java
public class Complex {
private double realPart; // 实部
private double imaginaryPart; // 虚部
// 构造函数
public Complex(double real, double imag) {
this.realPart = real;
this.imaginaryPart = imag;
}
// 获取实部和虚部的方法
public double getReal() { return realPart; }
public double getImaginary() { return imaginaryPart; }
// 加法方法
public Complex add(Complex other) {
double real = this.realPart + other.realPart;
double imag = this.imaginaryPart + other.imaginaryPart;
return new Complex(real, imag);
}
// 减法方法
public Complex subtract(Complex other) {
double real = this.realPart - other.realPart;
double imag = this.imaginaryPart - other.imaginaryPart;
return new Complex(real, imag);
}
// 打印复数的方法
@Override
public String toString() {
if (imaginaryPart == 0) {
return Double.toString(realPart) + " (实数)";
} else {
return Double.toString(realPart) + " + " + imaginaryPart + "i";
}
}
public static void main(String[] args) {
Complex c1 = new Complex(3, 4);
Complex c2 = new Complex(1, -2);
Complex sum = c1.add(c2);
Complex diff = c1.subtract(c2);
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1 + c2: " + sum);
System.out.println("c1 - c2: " + diff);
}
}
```
在这个例子中,我们定义了复数类的属性、构造函数以及基本的算术操作。`add`和`subtract`方法分别计算两个复数的和与差,然后返回新的`Complex`对象。
阅读全文