package day;
/**
*复数
* Mr.hao
*/
public class Complexnumber {
private double real;
private double imag;
/**
*构造器
*
*/
public Complexnumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
/**
*加
*
*/
public Complexnumber add(final Complexnumber r) {
return new Complexnumber(this.real + real, this.imag + r.imag);
}
/**
*减
*
*/
public Complexnumber sub(final Complexnumber r) {
return new Complexnumber(this.real - r.real, this.imag - r.imag);
}
/**
*乘
*
*/
public Complexnumber mul(final Complexnumber r) {
return new Complexnumber(this.real * r.real - this.real * r.imag,
this.imag * r.real + this.imag * r.imag);
}
@Override
public String toString() {
String realpart = real != 0 ? String.valueOf(real) : imag == 0 ? "0"
: "";
String imagpart = imag != 0 ? (imag > 0 ? "+" + imag : "-" + -imag)
+ "i" : "";
return realpart + imagpart;
}
}
package day;
/**
*测试
* Mr.hao
*/
public class Test002 {
public static void main(String[] args) {
Complexnumber r3 = new Complexnumber(0, 0);
Complexnumber r1 = new Complexnumber(-1, 1);
Complexnumber r2 = new Complexnumber(2, -2);
System.out.println(r3);
System.out.println("加:" + r1.add(r2));
System.out.println("减:" + r1.sub(r2));
System.out.println("乘:" + r1.mul(r2));
}
}