程序题:用Java写

来源:百度知道 编辑:UC知道 时间:2024/06/17 21:48:23
定义一个复数类,可以通过构造函数给复数对象赋值,实步和虚步是该类的私有属性,定义它与复数、实数相加和相减的方法。

package book.oo;

public class ComplexNumber implements Cloneable{

/** 复数的实部 */
private double realPart;

/** 复数的虚部 */
private double imaginaryPart;

/** 默认构造函数 */
public ComplexNumber() {
this.realPart = 0.0;
this.imaginaryPart = 0.0;
}

/**
* 构造函数
* @param a 实部
* @param b 虚部
*/
public ComplexNumber(double a, double b) {
this.realPart = a;
this.imaginaryPart = b;
}

/**
* 复数的加法运算。
* c = a + b的运算法则是:
* c.实部 = a.实部 + b.实部; c.虚部 = a.虚部 + b.虚部
* @param aComNum 加数
* @return
*/
public ComplexNumber add(ComplexNumber aComNum) {
if (aComNum == null) {
System.err.println("对象不能够为null!");
return new ComplexNumber();
}
return new ComplexNumber(this.realPart + aComNum.getRealPart(),
this.imaginaryPart + aComNum.getImaginaryPart());