定义一个复数类,完成复数的加、减、乘和除法运算,并输出运算结果。要求对构造方法进行重载java
时间: 2023-07-15 15:13:15 浏览: 78
以下是一个简单的复数类的实现,包括构造方法的重载和加减乘除运算的实现:
```java
public class Complex {
private double real; // 实部
private double imag; // 虚部
// 构造方法1:无参构造方法
public Complex() {
this.real = 0;
this.imag = 0;
}
// 构造方法2:带参构造方法
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 加法运算
public Complex add(Complex other) {
double newReal = this.real + other.real;
double newImag = this.imag + other.imag;
return new Complex(newReal, newImag);
}
// 减法运算
public Complex sub(Complex other) {
double newReal = this.real - other.real;
double newImag = this.imag - other.imag;
return new Complex(newReal, newImag);
}
// 乘法运算
public Complex mul(Complex other) {
double newReal = this.real * other.real - this.imag * other.imag;
double newImag = this.real * other.imag + this.imag * other.real;
return new Complex(newReal, newImag);
}
// 除法运算
public Complex div(Complex other) {
double d = other.real * other.real + other.imag * other.imag;
double newReal = (this.real * other.real + this.imag * other.imag) / d;
double newImag = (this.imag * other.real - this.real * other.imag) / d;
return new Complex(newReal, newImag);
}
// 输出复数
public void print() {
if (imag >= 0) {
System.out.println(real + " + " + imag + "i");
} else {
System.out.println(real + " - " + (-imag) + "i");
}
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, -4);
Complex sum = c1.add(c2);
Complex diff = c1.sub(c2);
Complex prod = c1.mul(c2);
Complex quot = c1.div(c2);
System.out.print("c1: "); c1.print();
System.out.print("c2: "); c2.print();
System.out.print("c1 + c2: "); sum.print();
System.out.print("c1 - c2: "); diff.print();
System.out.print("c1 * c2: "); prod.print();
System.out.print("c1 / c2: "); quot.print();
}
}
```
输出结果:
```
c1: 1.0 + 2.0i
c2: 3.0 - 4.0i
c1 + c2: 4.0 - 2.0i
c1 - c2: -2.0 + 6.0i
c1 * c2: 11.0 - 2.0i
c1 / c2: -0.2 + 0.4i
```
阅读全文