用java定义一个复数类Complex,能够创建复数对象,并且实现复数之间的加、减运算

问题描述:

用java定义一个复数类Complex,能够创建复数对象,并且实现复数之间的加、减运算
复数具有实部和虚部两部分,如2+5i就是一个复数,其中2为实部,5i为虚部;两复数相加时,实部与实部相加,虚部与虚部相加.两复数相减时,实部与实部相减,虚部与虚部相减.
如(2+5i)+(3-4i)=5+1i
(2+5i)-(3-4i)=-1+9i
现在要求定义一个复数类Complex,能够创建复数对象,并且实现复数之间的加、减运算,在main()函数中测试该类.
我需要全部代码,急用,

public class ComplexDemo {
// main方法
public static void main(String[] a) {
Complex b = new Complex(2,5);
Complex c = new Complex(3,-4);
System.out.println(b + "+" + c + "=" + b.add(c));
System.out.println(b + "-" + c + "=" + b.minus(c));
System.out.println(b + "*" + c + "=" + b.multiply(c));
System.out.println(b + "/" + c + "=" + b.divide(c));
}
}
// Complex类
class Complex {
private double m;// 实部
private double n;// 虚部
public Complex(double m,double n) {
this.m = m;
this.n = n;
}
// add
public Complex add(Complex c) {
return new Complex(m + c.m,n + c.n);
}
// minus
public Complex minus(Complex c) {
return new Complex(m - c.m,n - c.n);
}
// multiply
public Complex multiply(Complex c) {
return new Complex(m * c.m - n * c.n,m * c.n + n * c.m);
}
// divide
public Complex divide(Complex c) {
double d = Math.sqrt(c.m * c.m) + Math.sqrt(c.n * c.n);
return new Complex((m * c.m + n * c.n) / d,Math.round((m * c.n - n * c.m) / d));
}
public String toString() {
String rtr_str = "";
if (n > 0)
rtr_str = "(" + m + "+" + n + "i" + ")";
if (n == 0)
rtr_str = "(" + m + ")";
if (n rtr_str = "(" + m + n + "i" + ")";
return rtr_str;
}
}