该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
public class ComplexTest {
public static void main(String[] args) {
Complex c = new Complex(3,5);
Complex d = new Complex(2,2);
System.out .println("复数运算");
System.out .println("第一个复数>>" + c);
System.out .println("第二个复数>>" + d);
System.out .println("两复数相加");
System.out .println(c + " + " + d + " = " + c.add(d));
System.out .println(c + " + " + 2 + ")" + " = " + c.add(2));
System.out .println("两复数相减");
System.out .println(c + " - " + d + " = " + c.subtract(d));
System.out .println(c + " - " + 2 + ")" + " = " + c.subtract(2));
System.out .println("两复数相乘");
System.out .println(c + " * " + d + " = " + c.multiply(d));
System.out .println(c + " * " + 2 + ")" + " = " + c.multiply(2));
}
}
//声明复数类
class Complex{
private double real;
private double imaginary;
//构造方法
public Complex(){
this(0.0,0.0);
}
public Complex(double real, double imaginary){
this.real=real;
this.imaginary=imaginary;
}
public Complex(Complex c){
this(c.getReal(), c.getImaginary());
}
//get,set方法
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
//两个复数相加
public Complex add(double real){
return new Complex(this.real+real,this.imaginary);
}
public Complex add(Complex other){
return add(this,other);
}
private Complex add(Complex c1,Complex c2){
return new Complex(c1.real+c2.real,c1.imaginary+c2.imaginary);
}
//两个复数相减
public Complex subtract(double real){
return new Complex(this.real - real,this.imaginary);
}
public Complex subtract(Complex other){
return subtract(this, other);
}
private Complex subtract(Complex c1,Complex c2){
return new Complex(c1.real - c2.real,c1.imaginary - c2.imaginary);
}
//两个复数相乘
public Complex multiply(double c){
return new Complex(this.real * c,this.imaginary * c);
}
public Complex multiply(Complex other){
return multiply(this, other);
}
private Complex multiply(Complex c1, Complex c2){
return new Complex(c1.real* c2.real - c1.imaginary* c2.imaginary,
c1.real* c2.imaginary + c2.real* c1.imaginary);
}
public String toString(){
return"("+real+"+"+imaginary+"i"+")";
}
}