java实现复数运算
时间: 2023-07-20 13:17:22 浏览: 51
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 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 realPart = (this.real * other.real + this.imaginary * other.imaginary)
/ (other.real * other.real + other.imaginary * other.imaginary);
double imaginaryPart = (this.imaginary * other.real - this.real * other.imaginary)
/ (other.real * other.real + other.imaginary * other.imaginary);
return new Complex(realPart, imaginaryPart);
}
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}
```
使用示例:
```java
Complex a = new Complex(1, 2);
Complex b = new Complex(3, 4);
// 加法
Complex c = a.add(b);
System.out.println(c); // 输出 4.0 + 6.0i
// 减法
Complex d = a.subtract(b);
System.out.println(d); // 输出 -2.0 - 2.0i
// 乘法
Complex e = a.multiply(b);
System.out.println(e); // 输出 -5.0 + 10.0i
// 除法
Complex f = a.divide(b);
System.out.println(f); // 输出 0.44 + 0.08i
```
以上代码实现了复数的加、减、乘、除运算。