public class Complex{
private int x;
private int y;
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public Complex(){x=0;y=0;}
public Complex(int i,int j){
x=i;y=j;
}
public void showComp(){
if(x==0&&y==0){
System.out.println("0");
return;
}
String s1=""+((x==0)?"":x);
String s2="";
if(y>0)
s2="+"+(y==1?"":y)+"i";
if(y<0)
s2=(y==-1?"-":y)+"i";
System.out.println(s1+s2);
}
public Complex addComp(Complex c1,Complex c2){
return new Complex(c1.getX()+c2.getX(),c1.getY()+c2.getY());
}
public Complex subComp(Complex c1,Complex c2){
return new Complex(c1.getX()-c2.getX(),c1.getY()-c2.getY());
}
public Complex multiComp(Complex c1,Complex c2){
return new Complex(c1.getX()*c2.getX()-c1.getY()*c2.getY(),c1.getX()*c2.getY()+c2.getX()*c1.getY());
}
public boolean equalComp(Complex C1,Complex C2){
return c1.getX()==c2.getX()&&c1.getY()==c2.getY();
}
}
纯手打,八九不离十
学习中
public class Complex {
// 属性;
private int i;
private int j;
// 默认构造方法(无参构造)
public Complex() {
i = 0;
j = 0;
}
public Complex(int i, int j) {
this.i = i;
this.j = j;
}
// get set 方法
public int getRealPart() {
return i;
}
public int getImaginaryPart() {
return j;
}
public void setRealPart(int i) {
this.i = i;
}
void setImaginaryPart(int j) {
this.j = j;
}
// 显示
public String showComp() {
if(getImaginaryPart()>0)
return getRealPart() + "+" + getImaginaryPart() + "i";
else
return getRealPart() +"-"+(- getImaginaryPart()) + "i";
}
// 加法
public static Complex addComp(Complex c1, Complex c2) {
return new Complex(c1.getRealPart() + c2.getRealPart(),
c1.getImaginaryPart() + c2.getImaginaryPart());
}
// 减法
public static Complex subComp(Complex c1, Complex c2) {
return new Complex(c1.getRealPart() - c2.getRealPart(),
c1.getImaginaryPart() - c2.getImaginaryPart());
}
// 乘法
public static Complex multiComp(Complex c1, Complex c2) {
return new Complex(
c1.getRealPart() * c2.getRealPart() + c1.getImaginaryPart()
* c2.getImaginaryPart(),
c1.getRealPart() * c2.getImaginaryPart() +c2.getRealPart()
* c1.getImaginaryPart());
}
// 比较
public static boolean equalComp(Complex c1, Complex c2) {
if (c1.getRealPart() == c2.getRealPart()
&& c1.getImaginaryPart() == c2.getImaginaryPart())
return true;
else
return false;
}
public static void main(String args[]){
Complex z1 = new Complex(1, 2);
Complex z2 = new Complex(1, -2);
Complex z4=addComp(z1, z2);
Complex z5=subComp(z1, z2);
Complex z6=multiComp(z1, z2);
// 显示5+8i和5-8i
System.out.println(z1.showComp());
System.out.println(z2.showComp());
boolean z7=equalComp(z1, z2);
System.out.println(z4.showComp());
System.out.println(z5.showComp());
System.out.println(z6.showComp());
if(z7)System.out.println("z1和z2相等!");
else System.out.println("z1和z2不相等!");
}
}
小弟初学Java 不足之处,多多指教!