题目描述
写一个复数类,实现以下程序主函数中所需要的功能。
#include <iostream>
using namespace std;
class MyComplex
{
private:
double x,y;
public:
/* Implementation of MyComplex */
};
int main()
{
MyComplex z1;
MyComplex z2;
cin >> z1 >> z2;
cout << z1 + z2 <<endl;
cout << z1 - z2 <<endl;
cout << z1 * z2 <<endl;
cout << z1 / z2 <<endl;
cout << (z1 += z2) <<endl;
cout << (z1 -= z2) <<endl;
cout << (z1 *= z2) <<endl;
cout << (z1 /= z2) <<endl;
return 0;
}
输入格式
输入包括两行,第一行是两个整数a, b(0<|a|+1,|b|<100010<|a|+1,|b|<10001),表示复数a+bia+bi。
第二行是两个整数c, d(0<|c|+1,|d|<100010<|c|+1,|d|<10001),表示复数c+dic+di。输入数据保证不出现除以0的情况。
输出格式
输出包括八行,对应所给程序中的输出。注意输出浮点数保留2位小数。
Sample Input 1
3 6
-3 5
Sample Output 1
0.00 11.00
6.00 1.00
-39.00 -3.00
0.62 -0.97
0.00 11.00
3.00 6.00
-39.00 -3.00
3.00 6.00
Sample Input 2
5 9
5 -9
Sample Output 2
10.00 0.00
0.00 18.00
106.00 0.00
-0.53 0.85
10.00 0.00
5.00 9.00
106.00 0.00
5.00 9.00
代码:
#include <iostream>
#include <iomanip>
using namespace std;
class MyComplex{
private:
double x, y;
public:
MyComplex() {
x = 0;
y = 0;
}
MyComplex(double xx, double yy) {
x = xx;
y = yy;
}
friend ostream& operator << (ostream& output, MyComplex c) {
output << setiosflags(ios::fixed) << setprecision(2) << c.x << " " << c.y; // 保留两位
return output;
}
friend istream& operator >> (istream& input, MyComplex& c) {
input >> c.x >> c.y;
return input;
}
MyComplex operator + (const MyComplex& c) {
return MyComplex(x + c.x, y + c.y);
}
MyComplex operator - (const MyComplex& c) {
return MyComplex(x - c.x, y - c.y);
}
MyComplex operator * (const MyComplex& c) {
return MyComplex(x * c.x - y * c.y, x * c.y + y * c.x);
}
MyComplex operator / (const MyComplex& c) {
return MyComplex((x * c.x + y * c.y) / (c.x * c.x + c.y * c.y), ( - x * c.y + y * c.x) / (c.x * c.x + c.y * c.y));
}
MyComplex& operator += (const MyComplex& c) {
*this = *this + c;
return *this;
}
MyComplex& operator -= (const MyComplex& c) {
*this = *this - c;
return *this;
}
MyComplex& operator *= (const MyComplex& c) {
*this = *this * c;
return *this;
}
MyComplex& operator /= (const MyComplex& c) {
*this = *this / c;
return *this;
}
};
int main(int argc, char const *argv[]) {
MyComplex z1;
MyComplex z2;
cin >> z1 >> z2;
cout << z1 + z2 <<endl;
cout << z1 - z2 <<endl;
cout << z1 * z2 <<endl;
cout << z1 / z2 <<endl;
cout << (z1 += z2) <<endl;
cout << (z1 -= z2) <<endl;
cout << (z1 *= z2) <<endl;
cout << (z1 /= z2) <<endl;
return 0;
}
收获:
复习c++友元、运算符重载。