【问题描述】
创建一个复数类Complex,对复数进行数学运算,复数具有如下格式:realPart+imaginaryPart*i,其中,i为-1的平方根,具体要求如下:
(1)利用浮点变量表示此类的私有数据。提供两个构造方法,一个用于此类声明时对象的初始化;一个为带默认值得无参构造方法。
(2)提供两复数加、减、乘的运算方法。
(3)按格式(a,b)打印复数,其中a为实部,b为虚部。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("input c1:");
double r1 = in.nextDouble();
double ima1 = in.nextDouble();
System.out.println("input c2:");
double r2 = in.nextDouble();
double ima2 = in.nextDouble();
Complex c1 = new Complex(r1, ima1);
Complex c2 = new Complex(r2, ima2);
System.out.println("ComplexNumber a: "+c1);
System.out.println("ComplexNumber b: "+c2);
System.out.println("(a + b) = " + c1.add(c2));
System.out.println("(a - b) = " + c1.sub(c2));
System.out.println("(a * b) = " + c1.mul(c2));
}
}
class Complex {
private double real, imaginary;
Complex(double r, double i) {
this.imaginary = i;
this.real = r;
}
Complex() {
}
public Complex add(Complex other) {
Complex t = new Complex(0, 0);
t.real = this.real + other.real;
t.imaginary = this.imaginary + other.imaginary;
return t;
}
public Complex sub(Complex other) {
Complex t = new Complex(0, 0);
t.real = this.real - other.real;
t.imaginary = this.imaginary - other.imaginary;
return t;
}
public Complex mul(Complex other) {
Complex t = new Complex(0, 0);
t.real = this.real * other.real - this.imaginary * other.imaginary;
t.imaginary = this.real * other.imaginary + this.imaginary * other.real;
return t;
}
public String toString() {
return real + " + " + imaginary + "i";
}
}