复数的加减乘除JAVA
时间: 2024-10-25 12:09:10 浏览: 21
在Java中处理复数(Complex numbers),通常我们会创建一个名为`Complex`的类来封装实部(real part)和虚部(imaginary part)。复数的加减乘除操作可以按照数学规则来实现:
1. **构造函数**:用于初始化复数的值,如`Complex(double real, double imaginary)`。
```java
public class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
}
```
2. **加法(Addition)**:两个复数相加,实部加实部,虚部加虚部。
```java
public Complex add(Complex other) {
double sumReal = real + other.real;
double sumImaginary = imaginary + other.imaginary;
return new Complex(sumReal, sumImaginary);
}
```
3. **减法(Subtraction)**:类似于加法,只是方向相反。
```java
public Complex subtract(Complex other) {
double diffReal = real - other.real;
double diffImaginary = imaginary - other.imaginary;
return new Complex(diffReal, diffImaginary);
}
```
4. **乘法(Multiplication)**:涉及到分配律和i^2 = -1的特性。
```java
public Complex multiply(Complex other) {
double productReal = real * other.real - imaginary * other.imaginary;
double productImaginary = real * other.imaginary + imaginary * other.real;
return new Complex(productReal, productImaginary);
}
```
5. **除法(Division)**:更复杂一些,需要将除数转换为极坐标形式,并做相应计算。
```java
public Complex divide(Complex divisor) {
double denominatorSquare = divisor.real * divisor.real + divisor.imaginary * divisor.imaginary;
double quotientReal = (real * divisor.real + imaginary * divisor.imaginary) / denominatorSquare;
double quotientImaginary = (imaginary * divisor.real - real * divisor.imaginary) / denominatorSquare;
// 如果分母为零,抛出异常
if (denominatorSquare == 0) throw new ArithmeticException("Cannot divide by zero");
return new Complex(quotientReal, quotientImaginary);
}
```
阅读全文