1.定义复数类,包括实部和虚部变量、构造方法、 加减乘除方法、求绝对值方法和显示实部、虚部值的方法。 然后编写一个主类,在其主方法中通过定义两个复数对象来 显示每一个复数的实部值、虚部值和绝对值, 显示两个复数加减乘除结果。
package study; public class demo1 { public static void main(String[] args) throws Exception{ FuSu x=new FuSu(1,2); FuSu y=new FuSu(3,4); x.showa(); x.showb(); x.abs(); FuSu z1=FuSu.jia(x,y); FuSu z2=FuSu.jian(x,y); FuSu z3=FuSu.cheng(x,y); FuSu z4=FuSu.chu(x,y); System.out.println("jia:"+z1.a+"+"+z1.b+"i"); System.out.println("jia:"+z2.a+"+"+z2.b+"i"); System.out.println("jia:"+z3.a+"+"+z3.b+"i"); System.out.println("jia:"+z4.a+"+"+z4.b+"i"); } } class FuSu{ protected int a; protected int b; public FuSu(int a,int b){ this.a=a; this.b=b; } public static FuSu jia(FuSu x1,FuSu x2){ int a=x1.a+x2.a; int b=x1.b+x2.b; return new FuSu(a,b) ; } public static FuSu jian(FuSu x1,FuSu x2){ int a=x1.a-x2.a; int b=x1.b-x2.b; return new FuSu(a,b) ; } public static FuSu cheng(FuSu x1,FuSu x2){ int a=x1.a*x2.a-x1.b*x2.b; int b=x1.a*x2.b+x1.b*x2.a; return new FuSu(a,b); } public static FuSu chu(FuSu x1,FuSu x2) throws Exception{ if(x2.a==0){ throw new Exception("fusu2.a=0"); } if(x2.b==0){ throw new Exception("fusu2.b=0"); } int a=(x1.a*x2.a+x1.b*x2.b)/(x2.a*x2.a+x2.b*x2.b); int b=(x1.b*x2.a-x1.a*x2.b)/(x2.a*x2.a+x2.b*x2.b); return new FuSu(a,b); } public void showa(){ System.out.println(this.a); } public void showb(){ System.out.println(this.b); } public void abs(){ double x=Math.sqrt(this.a*this.a+this.b*this.b); System.out.println(x); }