定义一个复数类 complex
时间: 2024-09-13 12:14:48 浏览: 38
在编程中,定义一个复数类`complex`通常是为了处理复数的数学运算。复数是由实部和虚部组成的数,通常表示为 a + bi 的形式,其中 a 是实部,b 是虚部,i 是虚数单位,满足 i² = -1。一个简单的复数类定义可能包含以下内容:
```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 double getImaginary() {
return 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 newReal = this.real * other.real - this.imaginary * other.imaginary;
double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(newReal, newImaginary);
}
// 复数除法
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new Complex(newReal, newImaginary);
}
// 复数的字符串表示
@Override
public String toString() {
return "(" + real + " + " + imaginary + "i)";
}
}
```
这个类定义了一个复数的结构和基本操作,包括加、减、乘、除运算以及复数的字符串表示方法。使用这个类可以创建复数对象,并执行基本的复数运算。
阅读全文