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