Java 中的複數
複數是與虛部和實部相關聯的數字。它們可以像普通數字一樣進行加法和減法運算。實部和虛部可以分別進行加減法運算,甚至可以進行乘除法運算。
示例
public class Demo{
double my_real;
double my_imag;
public Demo(double my_real, double my_imag){
this.my_real = my_real;
this.my_imag = my_imag;
}
public static void main(String[] args){
Demo n1 = new Demo(76.8, 24.0),
n2 = new Demo(65.9, 11.23),
temp;
temp = add(n1, n2);
System.out.printf("The sum of two complex numbers is %.1f + %.1fi", temp.my_real,
temp.my_imag);
}
public static Demo add(Demo n1, Demo n2){
Demo temp = new Demo(0.0, 0.0);
temp.my_real = n1.my_real + n2.my_real;
temp.my_imag = n1.my_imag + n2.my_imag;
return(temp);
}
}輸出
The sum of two complex numbers is 142.7 + 35.2i
一個名為 Demo 的類定義了兩個雙精度值數字、my_real 和 my_imag。定義了一個建構函式,它接受這兩個值。在 main 函式中,建立了 Demo 類的例項,並且使用“add”函式新增元素,並將其分配給臨時物件(它在 main 函式中建立)。
接下來,它們顯示在控制檯上。在 main 函式中,建立了另一個臨時例項,並且分別新增複數的實部和虛部,並且返回此臨時物件作為輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP