直接上代码,不解释
public class ComplexNumber{
private float real ;
private float imaginary;
public ComplexNumber() {
super();
}
public ComplexNumber(float r, float i) {
super();
real=r;
imaginary=i;
}
public void setReal(float real) {
this.real = real;
}
public float getReal() {
return real;
}
public void setImaginary(float imaginary) {
this.imaginary =imaginary;
}
public float getImaginary() {
return imaginary;
}
public void add(ComplexNumber obj){
this.real += obj.real;
this.imaginary += obj.imaginary;
}
public void sub(ComplexNumber obj){
this.real -= obj.real;
this.imaginary -= obj.imaginary;
}
public void multiply(ComplexNumber obj){
this.real=this.real*obj.real-this.imaginary*obj.imaginary;
this.imaginary=this.imaginary*obj.real-this.real*obj.imaginary;
}
public String toString(){
if (imaginary==0)
return " real ";
if (imaginary>=0)
return real+"+"+imaginary+"i" ;
else
return real+""+imaginary+"i" ;
}
public static void main(String[] args){
ComplexNumber c=new ComplexNumber(1,2);
ComplexNumber d=new ComplexNumber(2,-7);
c.add(c);
System.out.println(c.toString());
d.add(d);
System.out.println(d.toString());
}
}