public class Complex {
private int entry;//实部
private int visual;//虚部
public Complex() {
super();
}
public Complex(int en, int vi) {
super();
this.setEntry(en);
this.setVisual(vi);
}
public int getEntry() {
return entry;
}
public void setEntry(int entry) {
this.entry = entry;
}
public int getVisual() {
return visual;
}
public void setVisual(int visual) {
this.visual = visual;
}
//显示:
public void showComp(){
System.out.println(this.getEntry()+"+"+this.getVisual()+"i");
}
//加法:
public Complex addComp(Complex c1,Complex c2){
int e = c1.entry + c2.entry;
int v = c1.visual + c2.visual;
Complex c = new Complex(e,v);
return c;
}
//减法:
public Complex subComp(Complex c1,Complex c2){
int e = c1.entry - c2.entry;
int v = c1.visual - c2.visual;
Complex c = new Complex(e,v);
return c;
}
//乘法:
public Complex multiComp(Complex c1,Complex c2){
int e = c1.entry*c2.entry - c1.visual*c2.visual;
int v = c1.visual*c2.entry + c1.entry*c2.visual;
Complex c = new Complex(e,v);
return c;
}
//相同返回true,不同返回false
public boolean equalComp(Complex c1,Complex c2){
return c1.entry==c2.entry && c1.visual == c2.visual;
}
}
//测试类
public class Test {
public static void main(String [] args){
//验证默认构造初始化:实部是0,虚部也是0
Complex c = new Complex();
System.out.print("默认构造结果是:");
System.out.println(c.getEntry());
System.out.println(c.getVisual());
//加法:
Complex c1 = new Complex(3,7);
Complex c2 = new Complex(5,6);
Complex cj = new Complex();
cj = c.addComp(c1,c2);
System.out.print("加法结果是:");
cj.showComp();
//减法:
Complex c3 = new Complex();
Complex c4 = new Complex();
Complex cm = new Complex();
cm = c.subComp(c1,c2);
System.out.print("减法结果是:");
cm.showComp();
//乘法:
Complex c5 = new Complex();
Complex c6 = new Complex();
Complex cc = new Complex();
cc = c.multiComp(c1,c2);
System.out.print("乘法结果是:");
cc.showComp();
//相等比较:
Complex c7 = new Complex(3,-3);
Complex c8 = new Complex(3,4);
Complex c9 = new Complex(3,4);
boolean resuls1 = c.equalComp(c7,c8);
boolean resuls2 = c.equalComp(c8,c9);
System.out.print("比较结果是:");
System.out.print(resuls1?true:false);
System.out.print(resuls2?true:false);
}
}
public class Complex {
int x;
int y;
public Complex() {
this.x = 0;
this.y = 0;
}
public Complex(int x,int y) {
this.x = x;
this.y = y;
}
public Complex addComp(Complex C1,Complex C2) {
return new Complex(C1.x + C2.x, C1.y + C2.y);
}
public Complex subComp(Complex C1,Complex C2) {
return new Complex(C1.x - C2.x, C1.y - C2.y);
}
public Complex multiComp(Complex C1,Complex C2) {
int newX = C1.x * C2.x - C1.y * C2.y;
int newY = C1.x * C2.y + C1.y * C1.x;
return new Complex(newX, newY);
}
public Complex multiComp(Complex C1,Complex C2) {
int newX = (C1.x * C2.x + C1.y * C2.y) / (C2.x * C2.x + C2.y * C2.y);
int newY = (C1.y * C2.x - C1.x * C2.y) / (C2.x * C2.x + C2.y * C2.y);
return new Complex(newX, newY);
}
public void showComp() {
System.out.print(x);
if(y > 0) {
System.out.println("+" + y + "i");
}
else {
System.out.println("-" + y + "i");
}
}
}
注释没写,但是很简单的逻辑,应该不难理解~~