共计 1400 个字符,预计需要花费 4 分钟才能阅读完成。
要实现一个 Java 复数类,你可以按照以下步骤进行:
- 创建一个名为 Complex 的类,并在该类中声明两个私有变量,用于表示复数的实部和虚部。可以使用 double 类型变量来表示这两个部分。
public class Complex {private double real;
private double imaginary;
// 构造方法、getter 和 setter 等其他方法
}
- 实现 Complex 类的构造方法,以便在创建 Complex 对象时初始化实部和虚部。
public Complex(double real, double imaginary) {this.real = real;
this.imaginary = imaginary;
}
- 提供 getter 和 setter 方法,用于获取和设置实部和虚部的值。
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;
}
-
实现复数加法和乘法的方法。可以使用以下公式计算两个复数的和和积:
- 复数加法:(a + bi) + (c + di) = (a + c) + (b + d)i
- 复数乘法:(a + bi) * (c + di) = (ac – bd) + (ad + bc)i
public Complex add(Complex other) {double realPart = this.real + other.real;
double imaginaryPart = this.imaginary + other.imaginary;
return new Complex(realPart, imaginaryPart);
}
public Complex multiply(Complex other) {double realPart = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryPart = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(realPart, imaginaryPart);
}
- 可选:实现 toString 方法,用于以字符串形式表示复数。
@Override
public String toString() {if (imaginary >= 0) {return real + " + " + imaginary + "i";
} else {return real + " - " + (-imaginary) + "i";
}
}
这样,你就可以使用这个 Complex 类来表示和操作复数了。例如:
Complex a = new Complex(2, 3);
Complex b = new Complex(4, -1);
Complex sum = a.add(b);
System.out.println("Sum: " + sum);
Complex product = a.multiply(b);
System.out.println("Product: " + product);
输出结果为:
Sum: 6.0 + 2.0i
Product: 11.0 + 10.0i
丸趣 TV 网 – 提供最优质的资源集合!
正文完