Problem Description
设有复数c=12.5+4.8i,双精度浮点数f=3.2,编写复数类(Complex),计算f+c、c+f和f-c的值。
完善以下程序。
//你的代码写在这里
int main()
{
Complex c(12.5, 4.8);
Complex t;
t = 3.2 + c;
t.Display();
t = c + 3.2;
t.Display();
t = 3.2 - c;
t.Display();
return 0;
}
Input Description
无
Sample Output
15.7+4.8i
15.7+4.8i
-9.3-4.8i
#include <iostream> using namespace std; class Complex { public: double a; double b; //构造函数 Complex(double c_a, double c_b) { a = c_a; b = c_b; } void Display() { cout << a; if (b > 0) cout << "+"; if (b != 0) //i<0时,直接输出负数i i!=0时,啥都不输出 cout << b << "i"; cout << endl; } Complex(){} }; //全局函数作运算符重载 Complex operator+(double num,Complex &p) { Complex t; t.a = num + p.a; t.b = p.b; return t; } Complex operator+(Complex& p, double num) { Complex t; t.a =p.a + num; t.b = p.b; return t; } Complex operator-(double num, Complex& p) { Complex t; t.a = num - p.a; t.b =0 - p.b; return t; } int main() { Complex c(12.5, 4.8); Complex t; t = 3.2 + c; t.Display(); t = c + 3.2; t.Display(); t = 3.2 - c; t.Display(); return 0; }
#include<iostream> using namespace std; class Complex { double r, i; public: Complex(double a = 0.0, double b = 0.0) { r = a; i = b; } friend Complex operator-(Complex a, Complex b) { Complex t; t.r = a.r - b.r; t.i = a.i - b.i; return t; } friend Complex operator+(Complex a, Complex b) { Complex t; t.r = a.r + b.r; t.i = a.i + b.i; return t; } void Display() { cout << r; if (i > 0) cout << "+"; if (i != 0) cout << i << "i"; cout << endl; } };