用java创建一个复数类Complex, 用来执行复 数的算术运算, 并编写一个程序来测试 该类. (1) 该类有两个成员变量,即实部 realPart和虚部imaginaryPart, 均为实数 类型 (2) 定义一个构造函数, 用来对类对 象进行初始化,构造函数的函数原型为: Complex(double r, double i); (3)定叉一介add成眞函数,実現両介 复数的加法 Complex add(Complex) (4)定叉一介minus成景函数,実現両 个复数的減法 Complex minus(Complex); (5)定文一介print成員函数,在扉幕 上打印当前复数, 打印格式为: 1.0+1.0i
时间: 2023-04-04 14:04:43 浏览: 415
我可以回答这个问题。以下是Java创建复数类Complex的代码:
public class Complex {
private double realPart;
private double imaginaryPart;
public Complex(double r, double i) {
realPart = r;
imaginaryPart = i;
}
public Complex add(Complex c) {
return new Complex(realPart + c.realPart, imaginaryPart + c.imaginaryPart);
}
public Complex minus(Complex c) {
return new Complex(realPart - c.realPart, imaginaryPart - c.imaginaryPart);
}
public void print() {
System.out.println(realPart + " " + imaginaryPart + "i");
}
}
以下是测试程序的代码:
public class TestComplex {
public static void main(String[] args) {
Complex c1 = new Complex(1.0, 2.0);
Complex c2 = new Complex(3.0, 4.0);
Complex c3 = c1.add(c2);
c3.print();
Complex c4 = c1.minus(c2);
c4.print();
}
}
运行结果如下:
4.0 6.0i
-2.0 -2.0i
希望这个回答能够帮到你!
阅读全文