Java 复数类

复数是由实部和虚部组成的数学对象,可以表示为 a + bi 的形式,其中 a 为实部,b 为虚部,i 为虚数单位。在Java中,我们可以使用复数类来方便地表示和操作复数。

复数类的设计

我们可以设计一个复数类 ComplexNumber,其中包括实部和虚部两个成员变量,以及相应的构造方法和操作方法。

类成员

  • real:实部
  • imaginary:虚部

构造方法

  • ComplexNumber(double real, double imaginary):根据给定的实部和虚部构造一个复数对象

操作方法

  • add(ComplexNumber other):将当前复数与另一个复数相加
  • subtract(ComplexNumber other):将当前复数与另一个复数相减
  • multiply(ComplexNumber other):将当前复数与另一个复数相乘
  • divide(ComplexNumber other):将当前复数与另一个复数相除
  • toString():将复数转换为字符串形式,方便输出
public class ComplexNumber {
    private double real;
    private double imaginary;

    public ComplexNumber(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    public void add(ComplexNumber other) {
        this.real += other.real;
        this.imaginary += other.imaginary;
    }

    public void subtract(ComplexNumber other) {
        this.real -= other.real;
        this.imaginary -= other.imaginary;
    }

    public void multiply(ComplexNumber other) {
        double newReal = this.real * other.real - this.imaginary * other.imaginary;
        double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
        this.real = newReal;
        this.imaginary = newImaginary;
    }

    public void divide(ComplexNumber other) {
        double denominator = other.real * other.real + other.imaginary * other.imaginary;
        double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
        double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
        this.real = newReal;
        this.imaginary = newImaginary;
    }

    public String toString() {
        return real + " + " + imaginary + "i";
    }
}

关系图

erDiagram
    ComplexNumber {
        double real
        double imaginary
    }

复数类的使用示例

public class Main {
    public static void main(String[] args) {
        ComplexNumber num1 = new ComplexNumber(1.0, 2.0);
        ComplexNumber num2 = new ComplexNumber(2.0, 3.0);

        num1.add(num2);
        System.out.println(num1.toString());

        num1.subtract(num2);
        System.out.println(num1.toString());

        num1.multiply(num2);
        System.out.println(num1.toString());

        num1.divide(num2);
        System.out.println(num1.toString());
    }
}

流程图

flowchart TD
    A[创建复数对象 num1] --> B[创建复数对象 num2]
    B --> C[num1 加 num2]
    C --> D[输出相加结果]
    D --> E[num1 减 num2]
    E --> F[输出相减结果]
    F --> G[num1 乘 num2]
    G --> H[输出相乘结果]
    H --> I[num1 除以 num2]
    I --> J[输出相除结果]

通过以上的示例代码和流程图,可以看到我们如何设计并使用Java中的复数类来进行复数的加减乘除操作。复数类的设计可以帮助我们更方便地处理复数运算,提高代码的可读性和可维护性。希望这篇文章对你理解Java复数类有所帮助。