1 /*题目:编写一个完整的Java程序使用复数类Comp1ex求两个复数1+2i和3+4i 的和(复数求和方法:实部与实部相加,虚部与虚部相加),
2 * 并将结果返回。
3 *复数类Comp1ex必须满足如下要求:
4 *题目:编写一个完整的Java程序使用复数类Comp1ex求两个复数1+2i和3+4i 的和(复数求和方法:实部与实部相加,虚部与虚部相加),
5 *并将结果返回。复数类Comp1ex必须满足如下要求:
6 *(1)复数类Complex 的属性有:
7 *realPart: int型,代表复数的实数部分
8 *imaginPart: int型,代表复数的虚数部分
9 *(2)复数类Comp1ex 的方法有:
10 *Comp1ex ( ) :构造函数,将复数的实部和虚部都置0.
11 *Complex ( int r , int i):构造方法,形参r为实部的初值,i为虚部的初值。Complex complexAdd (Complex a):
12 *将当前复数对象( this )与形参复数对象相加,所得的结杲仍是一个复数对象,并返回。public String toString ( ) :
13 *把当前复数对象的实部、虚部组合成a+bi 的字符串形式数对象的实部、虚部组合成a+bi
14 *的字符串形式(其中a和b分别为实部和虚部的数据),并将结果输出.
15 */
16
17
18
19 public class Complex
20 {
21 int realPart;
22 int imagInpart;
23 public Complex()
24 {
25 realPart = 0;
26 imagInpart = 0;
27 }
28 public Complex(int r, int i)
29 {
30 realPart = r;
31 imagInpart = i;
32 }
33 public Complex complexAdd(Complex a)
34 {
35 Complex b = new Complex();
36 b.realPart = realPart + a.realPart;
37 b.imagInpart = imagInpart + a.imagInpart;
38 return b;
39 }
40 public String toString()
41 {
42 return (realPart + "+" + imagInpart + "i");
43 }
44 }
45
1 import java.util.*;
2
3 public class p_Complex {
4 public static void main(String args[])
5 {
6 Scanner reader = new Scanner(System.in);
7 Complex c1 = new Complex(1, 2);
8 Complex c2 = new Complex(3, 4);
9 System.out.println("first complex:");
10 System.out.println(c1.toString());
11 System.out.println("second complex:");
12 System.out.println(c2.toString());
13 System.out.println("first+second=:");
14 System.out.print(c1.complexAdd(c2));
15 reader.close();
16 }
17 }