设计一个复数类,要求:
(1)在复数内部用双精度浮点数定义其实部和虚部;
(2)实现3个构造函数:无参(实部,虚部均为0)、1 个参数(参数赋值给实部,虚部为0)、2个参数(参数分别给实部虚部赋值);
(3)编写获取和修改复数的实部和虚部的成员方法;
(4)编写实现复数减法、乘法运算的成员方法;
(5)设计主方法,验证各成员方法的正确性;
ok,写好了:
public class Demo {
public static void main(String[] args) {
Complex complex1 = new Complex(20, 21);
Complex complex2 = new Complex(19, 99);
System.out.println("复数1为:" + complex1);
System.out.println("复数2为:" + complex2);
System.out.println("复数相减为:" + complex1.subtraction(complex2).toString());
System.out.println("复数相乘为:" + complex1.multiplication(complex2).toString());
}
}
/**
* 复数类
*/
class Complex {
private double real, imaginary;
public Complex() {
this(0, 0);
}
public Complex(double real) {
this(real, 0);
}
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
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;
}
/**
* 复数的减法
*
* @param complex 减数
* @return 相减以后的复数对象
*/
public Complex subtraction(Complex complex) {
return new Complex(this.getReal() - complex.getReal(), this.getImaginary() - complex.getImaginary());
}
/**
* 复数的乘法
*
* @param complex 乘数
* @return 相乘以后的复数对象 计算方法:(a+bi)(c+di)=(ac-bd)+(bc+ad)i。
*/
public Complex multiplication(Complex complex) {
double a = this.getReal(), b = this.getImaginary(), c = complex.getReal(), d = complex.getImaginary();
return new Complex(a * c - b * d, b * c + a * d);
}
@Override
public String toString() {
return real + "+" + imaginary + "i";
}
}