定义和实现复数类,可以完成复数的加减乘除及输出,Java 定义一个抽象类Shape,该类有抽象方法area,圆形、矩形、梯形等均是一种Shape,也都有自己求area方法,定义这些类并写测试类进行测试。Java
时间: 2024-10-19 13:13:05 浏览: 22
在Java中,我们可以创建一个名为`ComplexNumber`的类来代表复数,包含实部(real part)和虚部(imaginary part),然后提供相应的算术操作以及字符串输出的方法。以下是简单的实现:
```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 加法
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + other.real, this.imaginary + other.imaginary);
}
// 减法
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(this.real - other.real, this.imaginary - other.imaginary);
}
// 乘法
public ComplexNumber multiply(ComplexNumber other) {
double realPart = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryPart = this.real * other.imaginary + this.imaginary * other.real;
return new ComplexNumber(realPart, imaginaryPart);
}
// 除法 (假设除数非零)
public ComplexNumber divide(ComplexNumber divisor) {
double denominator = divisor.real * divisor.real + divisor.imaginary * divisor.imaginary;
double realPart = (this.real * divisor.real + this.imaginary * divisor.imaginary) / denominator;
double imaginaryPart = (this.imaginary * divisor.real - this.real * divisor.imaginary) / denominator;
return new ComplexNumber(realPart, imaginaryPart);
}
@Override
public String toString() {
if (imaginary >= 0) {
return String.format("%.2f + %.2fi", real, imaginary);
} else {
return String.format("%.2f - %.2fi", real, -imaginary);
}
}
}
// 对复数类进行测试
public class ComplexNumberTest {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(1, 2);
ComplexNumber c2 = new ComplexNumber(3, 4);
System.out.println("c1: " + c1); // 输出 1 + 2i
System.out.println("c1 + c2: " + c1.add(c2)); // 输出 4 + 6i
System.out.println("c1 - c2: " + c1.subtract(c2)); // 输出 -2 - 2i
ComplexNumber result = c1.multiply(c2);
System.out.println("c1 * c2: " + result); // 输出 5 - 10i
ComplexNumber reciprocal = c1.divide(new ComplexNumber(5, 0));
System.out.println("c1 / 5: " + reciprocal); // 输出 0.2 - 0.4i (假设浮点数除法准确)
}
}
```
在这个例子中,`ComplexNumber`是一个具体的类实现了`Shape`抽象类,但它不需要显式声明,因为我们直接处理复数的运算。`ComplexNumberTest`类用于测试复数的各种操作。
阅读全文