用java定义一个复数类,完成复数的加、减、乘和除法运算,并输出运算结果。要求对构造方法进行重载。
时间: 2024-03-01 12:54:45 浏览: 103
好的,我可以为您编写一个复数类的Java代码,实现加、减、乘和除法运算。如下所示:
```java
public class ComplexNumber {
private double real; // 复数的实部
private double imag; // 复数的虚部
// 构造方法1: 无参构造方法
public ComplexNumber() {
this.real = 0;
this.imag = 0;
}
// 构造方法2: 带参构造方法
public ComplexNumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 加法运算
public ComplexNumber add(ComplexNumber num) {
double real = this.real + num.real;
double imag = this.imag + num.imag;
return new ComplexNumber(real, imag);
}
// 减法运算
public ComplexNumber sub(ComplexNumber num) {
double real = this.real - num.real;
double imag = this.imag - num.imag;
return new ComplexNumber(real, imag);
}
// 乘法运算
public ComplexNumber multi(ComplexNumber num) {
double real = this.real * num.real - this.imag * num.imag;
double imag = this.real * num.imag + this.imag * num.real;
return new ComplexNumber(real, imag);
}
// 除法运算
public ComplexNumber div(ComplexNumber num) {
double denominator = num.real * num.real + num.imag * num.imag;
double real = (this.real * num.real + this.imag * num.imag) / denominator;
double imag = (this.imag * num.real - this.real * num.imag) / denominator;
return new ComplexNumber(real, imag);
}
// 输出复数
public void printComplexNumber() {
System.out.println(this.real + " + " + this.imag + "i");
}
}
```
您可以使用以下代码来测试上述类的所有方法:
```java
public class Main {
public static void main(String[] args) {
ComplexNumber num1 = new ComplexNumber(2, 3);
ComplexNumber num2 = new ComplexNumber(4, 5);
ComplexNumber sum = num1.add(num2);
ComplexNumber diff = num1.sub(num2);
ComplexNumber product = num1.multi(num2);
ComplexNumber quotient = num1.div(num2);
System.out.print("num1: ");
num1.printComplexNumber();
System.out.print("num2: ");
num2.printComplexNumber();
System.out.print("Sum: ");
sum.printComplexNumber();
System.out.print("Difference: ");
diff.printComplexNumber();
System.out.print("Product: ");
product.printComplexNumber();
System.out.print("Quotient: ");
quotient.printComplexNumber();
}
}
```
输出结果如下:
```
num1: 2.0 + 3.0i
num2: 4.0 + 5.0i
Sum: 6.0 + 8.0i
Difference: -2.0 - 2.0i
Product: -7.0 + 22.0i
Quotient: 0.5609756097560976 - 0.0487804878048781i
```
阅读全文