用Java设计一个复数类(Complex),成员变量包括实部(real)和虚部(image),成员方法有构造方法,更改器,获得器,toString的成员方法,两复数的加法add,两复数的减法substract等成员方法。
时间: 2024-05-01 11:16:49 浏览: 51
复数类(Complex)的Java代码:
```
public class Complex {
private double real;
private double image;
public Complex(double real, double image) {
this.real = real;
this.image = image;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImage() {
return image;
}
public void setImage(double image) {
this.image = image;
}
public String toString() {
if (image >= 0) {
return real + "+" + image + "i";
} else {
return real + "" + image + "i";
}
}
public Complex add(Complex c) {
double r = this.real + c.real;
double i = this.image + c.image;
return new Complex(r, i);
}
public Complex substract(Complex c) {
double r = this.real - c.real;
double i = this.image - c.image;
return new Complex(r, i);
}
}
```
使用方法:
```
Complex c1 = new Complex(2, 3);
Complex c2 = new Complex(4, 5);
Complex c3 = c1.add(c2);
System.out.println(c3.toString()); // 输出:6+8i
Complex c4 = c1.substract(c2);
System.out.println(c4.toString()); // 输出:-2-2i
```