public Complex ConjugateComNum(){ //返回共轭复数 this.imaginPart *= -1; returnthis; }
public boolean equals(Complex a){ if (this == a) returntrue; if (a == null || getClass() != a.getClass()) returnfalse; returnthis.realPart == a.realPart && this.imaginPart == a.imaginPart; }
@Override public String toString(){ DecimalFormat df = new DecimalFormat("#.##"); String rp = df.format(this.realPart); String ip = df.format(this.imaginPart); String result = ""; if (this.realPart != 0) { if (this.imaginPart == 0) result = rp; elseif (this.imaginPart == 1) result = rp + "+i"; elseif (this.imaginPart == -1) result = rp + "-i"; elseif (this.imaginPart > 0) result = rp + "+" + ip + "i"; else result = rp + ip + "i"; } else { if (this.imaginPart == 0) result = "0"; elseif (this.imaginPart == 1) result = "i"; elseif (this.imaginPart == -1) result = "-i"; else result = ip + "i"; } return result; }
/*@Override public String toString() { //保留两位小数 DecimalFormat df = new DecimalFormat("#.##"); String formatRealPart = df.format(this.realPart); String formatImaginPart = df.format(this.imaginPart); //处理虚部符号 正负 String symbol; if (imaginPart >= 0) { symbol = "+"; } else { symbol = ""; } //实部为0 if (realPart == 0) { //虚部也为0 if (imaginPart == 0) { return "0"; } //实部为0,虚部不为0且为整数 if (imaginPart % 1 == 0) { if (imaginPart == 1) { return "i"; } if (imaginPart == -1) { return "-i"; } return symbol + (int) imaginPart + "i"; } //虚部不为整数时 return symbol + formatImaginPart + "i"; } //否则实部不为0 //虚部为0,实部不为0 if (imaginPart == 0) { //实部为整数 if (realPart % 1 == 0) { return String.valueOf((int) realPart); } //实部不为整数 return formatRealPart; } //实部和虚部都不为0 //实部为整数 if (realPart % 1 == 0) { //虚部也为整数 if (imaginPart % 1 == 0) { //实部和虚部都为整数 if (imaginPart == 1) { return (int) realPart + symbol + "i"; //虚部为1 } if (imaginPart == -1) { //虚部为-1 return (int) realPart + "-i"; } return (int) realPart + symbol + (int) imaginPart + "i"; //实部和虚部都为整数 } else { return (int) realPart + symbol + formatImaginPart + "i"; //实部为整数,虚部不为整数 } //实部不为整数 } else if (imaginPart % 1 == 0) { return formatRealPart + symbol + (int) imaginPart + "i"; //只有虚部为整数 } else { return formatRealPart + symbol + formatImaginPart + "i"; //实部和虚部都不为整数 } }*/ }
publicstaticvoidprintComplexArray(){ //存入9个复数对象 方便检查 ArrayList<Complex> complexes = new ArrayList<>(Arrays.asList(new Complex(3, 2), new Complex(3, -2), new Complex(4, 1), new Complex(4, -1), new Complex(1, 0), new Complex(0, 0), new Complex(0, -2), new Complex(0, 1), new Complex(0, -1))); for (Complex complex : complexes) { System.out.print(complex + " "); } System.out.println(); } }