久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

java復數類怎么實現

134次閱讀
沒有評論

共計 1400 個字符,預計需要花費 4 分鐘才能閱讀完成。

要實現一個 Java 復數類,你可以按照以下步驟進行:

  1. 創建一個名為 Complex 的類,并在該類中聲明兩個私有變量,用于表示復數的實部和虛部。可以使用 double 類型變量來表示這兩個部分。
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. 實現復數加法和乘法的方法。可以使用以下公式計算兩個復數的和和積:

    • 復數加法:(a + bi) + (c + di) = (a + c) + (b + d)i
    • 復數乘法:(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

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-12-13發表,共計1400字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 朝阳县| 仙游县| 游戏| 晋宁县| 曲阳县| 广汉市| 历史| 玉溪市| 武乡县| 万山特区| 滨州市| 新干县| 仙居县| 井冈山市| 磐石市| 额尔古纳市| 卓尼县| 溆浦县| 潞城市| 科技| 饶阳县| 镇坪县| 龙山县| 台安县| 吉隆县| 浠水县| 灵石县| 高唐县| 毕节市| 平乐县| 霍城县| 商洛市| 陇南市| 云霄县| 香河县| 五常市| 永定县| 江口县| 酒泉市| 洪泽县| 蒲江县|