编写一个java程序复数类Complex
时间: 2023-12-18 21:03:51 浏览: 160
fushu.rar_Java 复数类_fushu_fushu java
Sure, I can help you with writing a Java program to create a Complex Number class. Here is the code:
public class Complex {
private double real;
private double imaginary;
public Complex(double r, double i) {
real = r;
imaginary = i;
}
public double getReal() {
return real;
}
public double getImaginary() {
return imaginary;
}
public Complex add(Complex c) {
return new Complex(real + c.real, imaginary + c.imaginary);
}
public Complex subtract(Complex c) {
return new Complex(real - c.real, imaginary - c.imaginary);
}
public Complex multiply(Complex c) {
double r = real * c.real - imaginary * c.imaginary;
double i = real * c.imaginary + imaginary * c.real;
return new Complex(r, i);
}
public Complex divide(Complex c) {
double denominator = c.real * c.real + c.imaginary * c.imaginary;
double r = (real * c.real + imaginary * c.imaginary) / denominator;
double i = (imaginary * c.real - real * c.imaginary) / denominator;
return new Complex(r, i);
}
public String toString() {
if (imaginary < 0) {
return real + " - " + (-imaginary) + "i";
}
return real + " + " + imaginary + "i";
}
}
I hope this helps! Let me know if you have any other questions.
阅读全文