JAVA定义一个复数类 Complex
时间: 2024-09-28 22:15:37 浏览: 43
在Java中,你可以通过创建一个名为Complex的类来定义一个复数类。复数通常由实部和虚部分组成,我们可以使用两个私有成员变量分别表示这两个部分。以下是一个简单的复数类的示例:
```java
public class Complex {
private double real; // 实部
private double imaginary; // 虚部
// 构造函数,初始化复数
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;
}
// 加法、减法、乘法和除法等基本操作的方法
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}
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);
}
public Complex divide(Complex other) {
if (other.real != 0 && other.imaginary == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double realPart = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double imaginaryPart = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new Complex(realPart, imaginaryPart);
}
// 重写toString()方法,方便打印复数
@Override
public String toString() {
return "(" + real + " + " + imaginary + "i)";
}
}
```
阅读全文