您的位置:首页 > 编程语言 > C语言/C++

C++:友元3(复数的加法)

2016-01-15 20:41 447 查看
C++:友元3(复数的加法)

Time Limit(Common/Java):1000MS/3000MS Memory Limit:65536KByte

Total Submit:353 Accepted:252

Description

定义复数类,用友元函数实现两个复数的加法。

Input

输入数据有若干行。每行上有四个整数,前两个表示一个复数的实部和虚部,后两个表示另一个复数的实部和虚部。

Output

对于每一组数据,输出两个复数的和,格式参照样例输出。

Sample Input

1 2 -3 -4

4 3 2 -1

1 2 -3 2

3 2 -3 1

Sample Output

-2-2i

6+2i

-2+4i

0+3i

代码块:

#include <iostream>

using namespace std;

class complex

{

int real,image;

public:

complex(int r=0 , int i=0);

friend complex add(complex &b, complex &c);

void show();

};

complex::complex(int r, int i)

{

real = r;

image = i;

}

void complex::show()

{

if(image<0)

cout<<real<<image<<"i"<<endl;

else cout<<real<<"+"<<image<<"i"<<endl;}

complex add(complex &b, complex &c)

{

int x, y;

x = b.real + c.real;

y = b.image + c.image;

return complex(x, y);

}

int main()

{

int a,b,c,d;

while (cin>>a>>b>>c>>d)

{

complex c1(a,b),c2(c,d),c3;

c3 = add(c1, c2);

c3.show();

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: