JAVA1.定义复数(Complex)类。要求:(1)复数有实部和虚部属性;(2)定义类的构造方法;(3)实现复数加减法并输出复数属性的值。(4)重载toString方法,用于对象属性值的输出。
时间: 2024-05-16 20:14:13 浏览: 47
下面是一个简单的Java实现,实现了复数类的定义、构造方法、复数加减法和toString方法的重载:
```java
public class Complex {
private double real; // 实部
private double imag; // 虚部
// 构造方法,初始化实部和虚部
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 复数加法
public Complex add(Complex other) {
double realSum = this.real + other.real;
double imagSum = this.imag + other.imag;
return new Complex(realSum, imagSum);
}
// 复数减法
public Complex subtract(Complex other) {
double realDiff = this.real - other.real;
double imagDiff = this.imag - other.imag;
return new Complex(realDiff, imagDiff);
}
// 重载toString方法,用于对象属性值的输出
public String toString() {
if (imag >= 0) {
return "(" + real + " + " + imag + "i)";
} else {
return "(" + real + " - " + (-imag) + "i)";
}
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) {
Complex a = new Complex(1, 2);
Complex b = new Complex(2, -1);
Complex c = a.add(b);
Complex d = a.subtract(b);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("a + b = " + c);
System.out.println("a - b = " + d);
}
}
```
输出结果:
```
a = (1.0 + 2.0i)
b = (2.0 - 1.0i)
a + b = (3.0 + 1.0i)
a - b = (-1.0 + 3.0i)
```
阅读全文