用java定义一个复数类,完成复数的加、减、乘和除法运算,并输出运算结果。要求对构造方法进行重载。并运用public static void main(String[] args) {
时间: 2024-03-01 20:55:17 浏览: 72
好的,我来为您实现一个Java的复数类,支持加、减、乘和除法运算:
```java
public class Complex {
private double real; // 实部
private double imag; // 虚部
// 构造方法重载
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex() {
this.real = 0;
this.imag = 0;
}
public Complex(double real) {
this.real = real;
this.imag = 0;
}
// 加法运算
public Complex add(Complex other) {
double real = this.real + other.real;
double imag = this.imag + other.imag;
return new Complex(real, imag);
}
// 减法运算
public Complex sub(Complex other) {
double real = this.real - other.real;
double imag = this.imag - other.imag;
return new Complex(real, imag);
}
// 乘法运算
public Complex mul(Complex other) {
double real = this.real * other.real - this.imag * other.imag;
double imag = this.real * other.imag + this.imag * other.real;
return new Complex(real, imag);
}
// 除法运算
public Complex div(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
double real = (this.real * other.real + this.imag * other.imag) / denominator;
double imag = (this.imag * other.real - this.real * other.imag) / denominator;
return new Complex(real, imag);
}
// 输出复数
public String toString() {
return real + " + " + imag + "i";
}
// 测试
public static void main(String[] args) {
Complex a = new Complex(2, 3);
Complex b = new Complex(4, -5);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("a + b = " + a.add(b));
System.out.println("a - b = " + a.sub(b));
System.out.println("a * b = " + a.mul(b));
System.out.println("a / b = " + a.div(b));
}
}
```
这个类包含了一个实部和一个虚部,以及加、减、乘、除四个运算方法,分别对应加法、减法、乘法和除法。构造方法重载有三种,一种是同时指定实部和虚部,一种是只指定实部,另一种是不指定任何值,实部和虚部默认为0。最后在`main`方法中进行了测试,输出运算结果。
希望这个例子可以帮助您理解复数类的实现。
阅读全文