用java。定义一个复数类,完成复数的加、减、乘和除法运算,并输出运算结果。要求对构造方法进行重载。
时间: 2024-02-28 17:56:56 浏览: 61
java编写一个类,该类可以进行加、减、乘、除四则运算,并且输出运算结果
好的,请看以下代码实现:
```java
public class ComplexNumber {
private double realPart; // 实部
private double imaginaryPart; // 虚部
// 无参构造方法
public ComplexNumber() {
this.realPart = 0;
this.imaginaryPart = 0;
}
// 有参构造方法
public ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
// 加法运算
public ComplexNumber add(ComplexNumber other) {
double newRealPart = this.realPart + other.realPart;
double newImaginaryPart = this.imaginaryPart + other.imaginaryPart;
return new ComplexNumber(newRealPart, newImaginaryPart);
}
// 减法运算
public ComplexNumber subtract(ComplexNumber other) {
double newRealPart = this.realPart - other.realPart;
double newImaginaryPart = this.imaginaryPart - other.imaginaryPart;
return new ComplexNumber(newRealPart, newImaginaryPart);
}
// 乘法运算
public ComplexNumber multiply(ComplexNumber other) {
double newRealPart = this.realPart * other.realPart - this.imaginaryPart * other.imaginaryPart;
double newImaginaryPart = this.realPart * other.imaginaryPart + this.imaginaryPart * other.realPart;
return new ComplexNumber(newRealPart, newImaginaryPart);
}
// 除法运算
public ComplexNumber divide(ComplexNumber other) {
double denominator = other.realPart * other.realPart + other.imaginaryPart * other.imaginaryPart;
double newRealPart = (this.realPart * other.realPart + this.imaginaryPart * other.imaginaryPart) / denominator;
double newImaginaryPart = (this.imaginaryPart * other.realPart - this.realPart * other.imaginaryPart) / denominator;
return new ComplexNumber(newRealPart, newImaginaryPart);
}
// 输出复数
public void print() {
System.out.println(this.realPart + " + " + this.imaginaryPart + "i");
}
}
```
然后我们可以在主函数中测试一下:
```java
public static void main(String[] args) {
ComplexNumber num1 = new ComplexNumber(2, 3);
ComplexNumber num2 = new ComplexNumber(4, -2);
System.out.print("num1: ");
num1.print();
System.out.print("num2: ");
num2.print();
System.out.print("num1 + num2 = ");
num1.add(num2).print();
System.out.print("num1 - num2 = ");
num1.subtract(num2).print();
System.out.print("num1 * num2 = ");
num1.multiply(num2).print();
System.out.print("num1 / num2 = ");
num1.divide(num2).print();
}
```
输出结果如下:
```
num1: 2.0 + 3.0i
num2: 4.0 + -2.0i
num1 + num2 = 6.0 + 1.0i
num1 - num2 = -2.0 + 5.0i
num1 * num2 = 16.0 + 8.0i
num1 / num2 = 0.1 + 0.7i
```
阅读全文