用Java设计一个复数类complex
时间: 2024-05-19 21:16:05 浏览: 50
public class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public Complex add(Complex c) {
return new Complex(real + c.real, imag + c.imag);
}
public Complex subtract(Complex c) {
return new Complex(real - c.real, imag - c.imag);
}
public Complex multiply(Complex c) {
return new Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
public Complex divide(Complex c) {
double denominator = c.real * c.real + c.imag * c.imag;
return new Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
public double magnitude() {
return Math.sqrt(real * real + imag * imag);
}
public Complex negate() {
return new Complex(-real, -imag);
}
public String toString() {
if (imag >= 0) {
return real + " + " + imag + "i";
} else {
return real + " - " + (-imag) + "i";
}
}
}
阅读全文