java复数的加减乘除
时间: 2024-10-28 16:04:15 浏览: 9
在Java中,复数是由实部和虚部组成的一对数值,通常表示为a + bi的形式,其中a是实部,b是虚部,i代表虚数单位,其满足i² = -1。Java并没有内置复数类型,但我们可以通过自定义类或者使用第三方库如`java.util.Complex`来处理复数。
如果你需要自定义实现,可以创建一个名为Complex的类,包含两个double类型的属性(real和imaginary),并提供加法、减法、乘法和除法的方法:
```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) {
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);
}
// 除法(假设除数不为0)
public Complex divide(Complex divisor) {
double denominator = divisor.real * divisor.real + divisor.imaginary * divisor.imaginary;
return new Complex((this.real * divisor.real + this.imaginary * divisor.imaginary) / denominator,
(this.imaginary * divisor.real - this.real * divisor.imaginary) / denominator);
}
}
// 使用示例
Complex c1 = new Complex(3, 4);
Complex c2 = new Complex(1, 2);
Complex sum = c1.add(c2);
Complex difference = c1.subtract(c2);
Complex product = c1.multiply(c2);
Complex quotient = c1.divide(c2); // 假设c2非零
```
阅读全文