java声明复数的类complex,实现复数的加减乘除运算。
时间: 2024-03-11 17:46:47 浏览: 149
以下是JAVA声明复数的类Complex,实现复数的加减乘除运算:
```
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) {
double realPart = this.real + other.real;
double imaginaryPart = this.imaginary + other.imaginary;
return new Complex(realPart, imaginaryPart);
}
// 复数减法
public Complex subtract(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);
}
// 复数除法
public Complex divide(Complex other) {
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);
}
// 复数转字符串
public String toString() {
if (imaginary == 0) {
return Double.toString(real);
} else if (real == 0) {
return Double.toString(imaginary) + "i";
} else {
return Double.toString(real) + (imaginary > 0 ? "+" : "-") + Double.toString(Math.abs(imaginary)) + "i";
}
}
}
```
使用方法如下:
```
Complex a = new Complex(1, 2);
Complex b = new Complex(3, 4);
Complex c = a.add(b);
System.out.println(a + " + " + b + " = " + c);
Complex d = a.subtract(b);
System.out.println(a + " - " + b + " = " + d);
Complex e = a.multiply(b);
System.out.println(a + " * " + b + " = " + e);
Complex f = a.divide(b);
System.out.println(a + " / " + b + " = " + f);
```
运行结果如下:
```
1.0+2.0i + 3.0+4.0i = 4.0+6.0i
1.0+2.0i - 3.0+4.0i = -2.0-2.0i
1.0+2.0i * 3.0+4.0i = -5.0+10.0i
1.0+2.0i / 3.0+4.0i = 0.44+0.08i
```
阅读全文