java复数的加减乘除PTA
时间: 2024-02-04 17:09:49 浏览: 33
在Java中,复数可以使用自定义的类来表示和操作。下面是一个简单的复数类的示例:
```java
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 realSum = this.real + other.real;
double imaginarySum = this.imaginary + other.imaginary;
return new Complex(realSum, imaginarySum);
}
public Complex subtract(Complex other) {
double realDiff = this.real - other.real;
double imaginaryDiff = this.imaginary - other.imaginary;
return new Complex(realDiff, imaginaryDiff);
}
public Complex multiply(Complex other) {
double realProduct = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryProduct = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(realProduct, imaginaryProduct);
}
public Complex divide(Complex other) {
double denominator = Math.pow(other.real, 2) + Math.pow(other.imaginary, 2);
double realQuotient = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double imaginaryQuotient = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new Complex(realQuotient, imaginaryQuotient);
}
@Override
public String