java複数はどのように実装されますか

ネイティブなJava複素数クラスを実装する手順は次のとおりです。

  1. 複素数の実部と虚部を表す2つのプライベート変数をdouble型の変数を使用して宣言するComplexというクラスを作成します。
public class Complex {
    private double real;
    private double imaginary;
    
    // 构造方法、getter和setter等其他方法
}
  1. Complexクラスのコンストラクタを実装し、Complexオブジェクトを作成するときに実部と虚部を初期化する。
public Complex(double real, double imaginary) {
    this.real = real;
    this.imaginary = imaginary;
}
  1. 実数部と虚数部の値を取得、設定するためのgetterとsetterメソッドを提供する。
public double getReal() {
    return real;
}

public void setReal(double real) {
    this.real = real;
}

public double getImaginary() {
    return imaginary;
}

public void setImaginary(double imaginary) {
    this.imaginary = imaginary;
}
  1. 複数の複素数の加算と乗算をする方法は以下の公式を使用して、2 つの複素数の和と積を計算できます:
  2. 複素数の加法:(a + bi) + (c + di) = (a + c) + (b + d)i
  3. 複素数の掛け算:(a + bi) * (c + di) = (ac – bd) + (ad + bc)i
public Complex add(Complex other) {
    double realPart = this.real + other.real;
    double imaginaryPart = this.imaginary + other.imaginary;
    return new Complex(realPart, imaginaryPart);
}

public Complex multiply(Complex other) {
    double realPart = this.real * other.real - this.imaginary * other.imaginary;
    double imaginaryPart = this.real * other.imaginary + this.imaginary * other.real;
    return new Complex(realPart, imaginaryPart);
}
  1. 複素数の文字列表現用のtoStringメソッドを実装できるとよい。
@Override
public String toString() {
    if (imaginary >= 0) {
        return real + " + " + imaginary + "i";
    } else {
        return real + " - " + (-imaginary) + "i";
    }
}

複素数の表現や操作にこのComplexクラスを使用できます。たとえば、

Complex a = new Complex(2, 3);
Complex b = new Complex(4, -1);

Complex sum = a.add(b);
System.out.println("Sum: " + sum);

Complex product = a.multiply(b);
System.out.println("Product: " + product);

日本語ネイティブによる言い換え:

Sum: 6.0 + 2.0i
Product: 11.0 + 10.0i
bannerAds