复数的运算(类和对象)

Problem Description
设计一个类Complex,用于封装对复数的下列操作:
成员变量:实部real,虚部image,均为整数变量;
构造方法:无参构造方法、有参构造方法(参数2个)
成员方法:含两个复数的加、减、乘操作。
    复数相加举例: (1+2i)+(3+4i)= 4 + 6i
    复数相减举例: (1+2i)-(3+4i)= -2 - 2i
    复数相乘举例: (1+2i)*(3+4i)= -5 + 10i
要求:对复数进行连环运算。
Input

输入有多行。
第一行有两个整数,代表复数X的实部和虚部。
后续各行的第一个和第二个数表示复数Y的实部和虚部,第三个数表示操作符op1——复数XY相加;2——复数XY相减;3——复数XY相乘。

Output

计算数据输出其简化复数形式,如:-2-2i、-4、-3i1+2i0

Example Input
1 1
3 4 2
5 2 1
2 -1 3
0 2 2
Example Output
5-7i
Hint
输入与输出形式示例:
如果输入:
2 3
-2 1 1
则输出:4i
如果输入:
1 2
-1 -2 1
则输出:0

复数的输出形式示例:
实部   虚部    输出形式
  0     0      0
  -4    0      -4
  0     4      4i
  3     2     3+2i
  3    -2     3-2i
Author
import java.util.Scanner;

public class Main {

	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     Scanner in = new Scanner(System.in); 
    	 int n = in.nextInt();
    	 int m = in.nextInt();
    	 Complex cc = new Complex(n,m);
    	 while(in.hasNext()){
    		 n = in.nextInt();
    		 m = in.nextInt();
    		 int o = in.nextInt();
    	 if(o == 1)
    		 cc.add(n, m);
    	 else if(o == 2)
    		 cc.sub(n, m);
    	 else if(o == 3)
    		 cc.mul(n, m);
    	 }
if(cc.real == 0 && cc.image == 1){
	System.out.println("i");
}	
else if(cc.real == 0 && cc.image == -1){
	System.out.println("-i");
}
else if(cc.real ==0 && cc.image != 0){
	System.out.println(cc.image+"i");
}
else if(cc.real ==0 && cc.image == 0){
	System.out.println("0");
}
else if(cc.real !=0 && cc.image == 0){
	System.out.println(cc.real);
}
else if(cc.real !=0 && cc.image == 1){
	System.out.println(cc.real+"+i");
}
else if(cc.real !=0 && cc.image == -1){
	System.out.println(cc.real+"-i");
}
else if(cc.real !=0 && cc.image > 0){
	System.out.println(cc.real+"+"+cc.image+"i");
}
else if(cc.real !=0 && cc.image < 0){
	System.out.println(cc.real+""+cc.image+"i");
}
}
}
 class Complex {
	   public int real;  
	    public int image; 
	   public Complex(int n,int m){
	    	real = n;
	    	image = m;
	    }
	   public void add(int n,int m){
		   real +=n;
		   image +=m;
	   }
	   public void sub(int n,int m){
		   real -=n;
		   image -=m;
	   }
	   public void mul(int n,int m){
		int h = real * n - image * m;
		 image = real * m+ image * n;
		 real = h;
	   }
	}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值