Java复数类设计与实现
本部分代码实现了一个简单的复数类 Complex
,包含实部和虚部属性,并实现了加法、减法和比较运算。
public class Complex {
private double real; // 实部
private double imag; // 虚部
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 加法
public Complex add(Complex other) {
double newReal = this.real + other.real;
double newImag = this.imag + other.imag;
return new Complex(newReal, newImag);
}
// 减法
public Complex subtract(Complex other) {
double newReal = this.real - other.real;
double newImag = this.imag - other.imag;
return new Complex(newReal, newImag);
}
// 比较是否相等
public boolean equals(Complex other) {
return this.real == other.real && this.imag == other.imag;
}
@Override
public String toString() {
return real + " + " + imag + "i";
}
// 测试代码
public static void main(String[] args) {
Complex c1 = new Complex(1.0, 2.0);
Complex c2 = new Complex(3.0, 4.0);
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
Complex sum = c1.add(c2);
System.out.println("c1 + c2: " + sum);
Complex diff = c1.subtract(c2);
System.out.println("c1 - c2: " + diff);
boolean isEqual = c1.equals(c2);
System.out.println("c1 equals c2: " + isEqual);
}
}
代码说明:
Complex
类包含两个私有成员变量real
和imag
,分别表示复数的实部和虚部。- 构造函数用于初始化复数对象。
add
方法实现两个复数的加法运算。subtract
方法实现两个复数的减法运算。equals
方法判断两个复数是否相等。toString
方法返回复数的字符串表示形式。
4.25KB
文件大小:
评论区