编写一个复数类ComplexNumber,满足以下要求: (1)覆盖其Object.toString()方法,向外界返回“a+bi”形式的字串,此方法的声明为:public String toString() (2)提供相应方法,完成复数的加减乘除和取模运算。
时间: 2023-06-08 12:06:34 浏览: 88
好的,我明白了您的要求。以下是ComplexNumber类的代码:
```
public class ComplexNumber {
private double real; // 实部
private double imag; // 虚部
// 构造函数
public ComplexNumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 覆盖toString()方法,返回“a bi”形式的字符串
public String toString() {
if (imag >= 0) {
return String.format("%.2f + %.2fi", real, imag);
} else {
return String.format("%.2f - %.2fi", real, -imag);
}
}
// 加法运算
public ComplexNumber add(ComplexNumber other) {
double newReal = real + other.real;
double newImag = imag + other.imag;
return new ComplexNumber(newReal, newImag);
}
// 减法运算
public ComplexNumber subtract(ComplexNumber other) {
double newReal = real - other.real;
double newImag = imag - other.imag;
return new ComplexNumber(newReal, newImag);
}
// 乘法运算
public ComplexNumber multiply(ComplexNumber other) {
double newReal = real * other.real - imag * other.imag;
double newImag = real * other.imag + imag * other.real;
return new ComplexNumber(newReal, newImag);
}
// 除法运算
public ComplexNumber divide(ComplexNumber other) {
double denom = other.real * other.real + other.imag * other.imag;
double newReal = (real * other.real + imag * other.imag) / denom;
double newImag = (imag * other.real - real * other.imag) / denom;
return new ComplexNumber(newReal, newImag);
}
// 取模运算
public double modulus() {
return Math.sqrt(real * real + imag * imag);
}
}
```
希望我能够回答您的问题。
阅读全文