Java关于复数类——Complex(复习与应用)
复数 (Complex) 工具需求分析
我的教主(编程启蒙老师)曾经说过:“需求分析”,这是软件工程的一个名词。其主要意思是:确定未来软件(程序)要实现的功能。这是编程前非常重要的一步,是后期开发的基础。如果“需求”不清楚,那么就谈不上代码的实现。而且,在确定需求时,是不考虑其具体实现的。总之,需求分析就是确定未来要开发的程序应该实现哪些功能。
复数的概念在高中数学就提出了,它由“实部”和“虚部"两部分组成,且,实部和虚部的取值在实数范围内。
复数有两种基本的表达方法,除了上述的实部、虚部表示方法外,还可以在极坐标的基础上,由角度和模这两个数据构成(向量表达方式)。下面要实现的复数工具,不需要用向量方式实现。
除了表达数值外,复数工具应该实现复数的四则运算,即(加、减、乘和除运算)和简单的输出。
Complex 类代码实现
public 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(double real) {
this(real, 0.0);
}
public Complex(Complex one) {
this(one.real, one.imaginary);
}
/**
* c1+c2
* c3 = c1 + c2 / c1 += c2
* @return
* @HB
*/
//加法
public Complex add(Complex one) {
this.real += one.real ;
this.imaginary += one.imaginary;
return this;
}
public static Complex add(Complex one, Complex other) {
Complex result = new Complex();
result.real = one.real + other.real ;
result.imaginary = one.imaginary +other.imaginary ;
return result;
}
public static Complex opposite(Complex one) {
return new Complex(-one.real ,-one.imaginary );
}
//减法
public Complex sub(Complex one) {
return this.add(Complex.opposite(one));
}
public static Complex sub(Complex one, Complex other) {
return new Complex(one).add(Complex.opposite(other));
}
//乘法
public Complex mul(Complex one) {
this.real = this.real * one.real - this.imaginary *one.imaginary ;
this.imaginary = this.real * one.imaginary + this.imaginary * one.real ;
return this;
}
public static Complex mul(Complex one,Complex other) {
return new Complex(one).mul(other);
}
//除法
public Complex div(Complex one) {
this.real = (this.real * one.real + this.imaginary *one.imaginary) / (one.real * one.real + one.imaginary * one.imaginary);
this.imaginary = (this.imaginary * one.real - this.real * one.imaginary ) / (one.real * one.real + one.imaginary * one.imaginary);
return this;
}
public static Complex div(Complex one,Complex other) {
return new Complex(one).div(other);
}
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;
}
@Override
public String toString() {
if(this.real == 0.0) {
return this.imaginary + "i";
} else if(this.imaginary == 0.0) {
return this.real + "";
}else if(this.imaginary < 0.0 && this.real != 0.0) {
return this.real + "" + this.imaginary + "i";
}else if(this.imaginary == 0.0 && this.real == 0.0) {
return 0.0 + "";
}
return this.real + "+" + this.imaginary + "i";
}
@Override
public boolean equals(Object obj) {
if(obj == this) {
return true;
} else if(obj == null) {
return false;
} else if(!(obj instanceof Complex)) {
return false;
}
Complex tmp = (Complex)obj;
return Math.abs(this.real - tmp.real) < 1e-6 && Math.abs(this.imaginary - tmp.imaginary) < 1e-6;
}
}
HB