java,编写一个名为“复数”的类,包含复数的实部和虚部(数据成员),以及复数之间的基本算术运算:加、减(方法成员),并要求复数加减运算,程序运行中能对给定的复数进行运算,并输出运算的结果。
时间: 2023-05-27 07:04:58 浏览: 65
```
public class Complex {
private double realPart; //实部
private double imaginaryPart; //虚部
public Complex(double realPart, double imaginaryPart) { //构造方法
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public Complex add(Complex other) { //加法
double r = this.realPart + other.realPart;
double i = this.imaginaryPart + other.imaginaryPart;
return new Complex(r, i);
}
public Complex subtract(Complex other) { //减法
double r = this.realPart - other.realPart;
double i = this.imaginaryPart - other.imaginaryPart;
return new Complex(r, i);
}
public String toString() { //输出结果
if (this.imaginaryPart < 0) {
return this.realPart + "-" + (-this.imaginaryPart) + "i";
} else {
return this.realPart + "+" + this.imaginaryPart + "i";
}
}
}
```
测试:
```
public class Test {
public static void main(String[] args) {
Complex a = new Complex(3, 2);
Complex b = new Complex(1, -1);
Complex c = a.add(b);
Complex d = a.subtract(b);
System.out.println(a + " + " + b + " = " + c);
System.out.println(a + " - " + b + " = " + d);
}
}
```
输出:
```
3.0+2.0i + 1.0-1.0i = 4.0+1.0i
3.0+2.0i - 1.0-1.0i = 2.0+3.0i
```
阅读全文