创建一个复数类complex,以复数进行数学运算、复数具有如下格式:RealPart+ImaginaryRart*I ,其中,I为-1的平方根。
要求如下:
① 利用浮点变量表示此类的私有数据。提供两个构造方法,一个用于此类声明的对象的初始化;一个为默认的无参构造方法。
② 提供两复数加、减、乘的运算方法。
③ 按格式(a,b)打印复数。其中a为实部,b为虚部。
package Test_2;
import java.util.Scanner;
public class Complex {
private double RealPart;
private double ImaginaryPart;
public double getRealPart() {
return RealPart;
}
public void setRealPart(double realPart) {
this.RealPart = realPart;
}
public double getImaginaryPart() {
return ImaginaryPart;
}
public void setImaginaryPart(double imaginaryPart) {
this.ImaginaryPart = imaginaryPart;
}
public Complex() {
this.RealPart = 0.0;
this.ImaginaryPart = 0.0;
}//默认构造函数
public Complex(double a,double b) {
this.RealPart = a;
this.ImaginaryPart = b;
}//重载构造函数
public Complex Add(Complex c)
{
Complex add = new Complex(this.RealPart+c.RealPart,this.ImaginaryPart+c.ImaginaryPart);
return add;
}//加法
public Complex Sub(Complex c)
{
Complex sub = new Complex(this.RealPart-c.RealPart,this.ImaginaryPart-c.ImaginaryPart);
return sub;
}//减法
public Complex Mul(Complex c)
{
double Real = this.RealPart * c.RealPart - this.ImaginaryPart * c.ImaginaryPart;
double Imaginary = this.RealPart * c.ImaginaryPart + this.ImaginaryPart * c.RealPart;
Complex mul = new Complex(Real,Imaginary);
return mul;
}//乘法
public void Print(Complex c)
{
System.out.println("("+c.RealPart+","+c.ImaginaryPart+")");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("输入第一个复数的实部和虚部:");
Scanner in=new Scanner(System.in);
double a1 = in.nextDouble();
double b1 = in.nextDouble();
Complex c1 = new Complex(a1,b1);
System.out.println("输入第二个复数的实部和虚部:");
double a2 = in.nextDouble();
double b2 = in.nextDouble();
Complex c2 = new Complex(a2,b2);
System.out.println("两个复数之和为:");
c1.Print(c1.Add(c2));
System.out.println("两个复数之差为:");
c1.Print(c1.Sub(c2));
System.out.println("两个复数之积为:");
c1.Print(c1.Mul(c2));
}
}