编写一个复数类,可以进行复数加法和减法运算。编写一个包含main方法的类(应用程序)测试该复数类。要求该复数类至少包含一个无参的构造方法和一个带参的构造方法;数据成员包括复数的实部和虚部,为double类型;包括两个方法,分别实现复数的加法和减法运算。
代码
import java.util.Scanner;
public class ComplexNum {
double RealNum;
double ImagNum;
public ComplexNum() {
Scanner input=new Scanner(System.in);
RealNum=input.nextDouble();
ImagNum=input.nextDouble();
//ComplexNum(RealNum,ImagNum);
}
public ComplexNum(double RealNum,double ImagNum) {
this.RealNum=RealNum;
this.ImagNum=ImagNum;
}
public ComplexNum add(ComplexNum b) {
double RealNum1=this.RealNum;
double ImagNum1=this.ImagNum;
double LastReal=RealNum+RealNum1;
double LastImag=ImagNum+ImagNum1;
ComplexNum result=new ComplexNum(LastReal,LastImag);
return result;
}
public ComplexNum mul(ComplexNum b) {
double RealNum1=this.RealNum;
double ImagNum1=this.ImagNum;
double LastReal=RealNum-RealNum1;
double LastImag=ImagNum-ImagNum1;
ComplexNum result=new ComplexNum(LastReal,LastImag);
return result;
}
public void printf() {
if(ImagNum>0) {
System.out.println(ImagNum+"+"+"j"+RealNum);
}
else if(ImagNum<0) {
System.out.println(ImagNum+"-"+"j"+RealNum);
}
else {
System.out.println(RealNum);
}
}
public static void main(String[] args) {
System.out.println("请输入第一个复数的实部和虚部");
ComplexNum a=new ComplexNum();
System.out.println("请输入第二个复数的实部和虚部");
ComplexNum b=new ComplexNum();
ComplexNum add=a.add(b);
ComplexNum mul=a.mul(b);
add.printf();
mul.printf();
}
}
第五若雪
相关分类