Java实现:创建一个复数类Complex,用来执行复数的算术运算,并编写一个程序来测试该类。 (1)该类有两个成员变量,即实部realPart和虚部imaginaryPart,均为实数类型 (2)定义一个构造函数,用来对类对象进行初始化,构造函数的函数原型为: Complex(double r, double i); (3)定义一个add成员函数,实现两个复数的加法 Complex add(Complex); (4)定义一个sub成员函数,实现两个复数的减法 Complex sub(Complex); (5)定义一个print成员函数,在屏幕上打印当前复数,打印格式为:1+1i
时间: 2024-03-26 16:35:17 浏览: 105
利用java实现复数类
好的,以下是Java实现的代码:
```
public class Complex {
private double realPart; // 实部
private double imaginaryPart; // 虚部
public Complex(double r, double i) { // 构造函数
realPart = r;
imaginaryPart = i;
}
public Complex add(Complex c) { // 加法
double real = realPart + c.realPart;
double imaginary = imaginaryPart + c.imaginaryPart;
return new Complex(real, imaginary);
}
public Complex sub(Complex c) { // 减法
double real = realPart - c.realPart;
double imaginary = imaginaryPart - c.imaginaryPart;
return new Complex(real, imaginary);
}
public void print() { // 打印当前复数
System.out.printf("%.1f+%.1fi", realPart, imaginaryPart);
}
}
```
接下来,我们可以编写一个测试程序来测试该类:
```
public class TestComplex {
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
Complex c3 = c1.add(c2);
Complex c4 = c1.sub(c2);
System.out.print("c1 = ");
c1.print();
System.out.println();
System.out.print("c2 = ");
c2.print();
System.out.println();
System.out.print("c3 = ");
c3.print();
System.out.println();
System.out.print("c4 = ");
c4.print();
System.out.println();
}
}
```
输出结果为:
```
c1 = 1.0+2.0i
c2 = 3.0+4.0i
c3 = 4.0+6.0i
c4 = -2.0-2.0i
```
以上就是Java实现复数类的代码和测试程序。
阅读全文