复数由两个部分组成:实数部分和虚数部分。复数的一种书写方式是:(3.0, 4.0),其中,3.0 是实数部分。4.0 是虚数部分。 假设a=(A,Bi),c=(C,Di),则下面是一些复数运算 加法: a+c=(A+C,(B+D)i) 减法: a-c=(A+C,(B+D)i) 乘法: a*c=(A*C-B*D,(A*D+B*C)i) 数乘: x*c=(x*C,x*Di) 共轭: ~a=(A,-Bi) 请定义一个复数类,以便下面的程序可以使用它来获得正确的结果。(提示:需要重载"<<"及">>",数乘运算最好通过友元函数重载)int main(){ complex a(3,4); complex c; cout<<"Enter a complex number (q to quit):"<<endl; while(cin>>c) { cout<<"c is "<<c<<endl; cout<<"complex conjugate is "<<~c<<endl; cout<<"a is "<<a<<endl; cout<<"a+c is "<<a+c<<endl; cout<<"a-c is "<<a-c<<endl; cout<<"a*c is "<<a*c<<endl; cout<<"2*c is "<<2*c<<endl; cout<<"Enter a complex number (q to quit):"<<endl; } cout<<"Done!"<<endl; return 0;}输入 输出示例:(其中 带有下划线的较大号的斜体字:1.2,2.3,q是输入,其他是输出信息)Enter a complex number (q to quit):real:1.2imag:2.3c is (1.2,2.3i)complex conjugate is (1.2,-2.3i)a is (3,4i)a+c is (4.2,6.3i)a-c is (1.8,1.7i)a*c is (-5.6,11.7i)2*c is (2.4,4.6i)Enter a complex number (q to quit):real:qDone!
时间: 2023-06-01 11:01:47 浏览: 179
#include <iostream>
using namespace std;
class complex {
private:
double real;
double imag;
public:
complex(double r = 0, double i = 0) : real(r), imag(i) {}
friend istream& operator>>(istream& is, complex& c);
friend ostream& operator<<(ostream& os, const complex& c);
friend complex operator+(const complex& a, const complex& b);
friend complex operator-(const complex& a, const complex& b);
friend complex operator*(const complex& a, const complex& b);
friend complex operator*(const double& x, const complex& c);
friend complex operator*(const complex& c, const double& x);
complex operator~() const;
};
istream& operator>>(istream& is, complex& c) {
cout << "real:";
is >> c.real;
if (!is) return is;
cout << "imag:";
is >> c.imag;
return is;
}
ostream& operator<<(ostream& os, const complex& c) {
os << "(" << c.real << "," << c.imag << "i)";
return os;
}
complex operator+(const complex& a, const complex& b) {
return complex(a.real + b.real, a.imag + b.imag);
}
complex operator-(const complex& a, const complex& b) {
return complex(a.real - b.real, a.imag - b.imag);
}
complex operator*(const complex& a, const complex& b) {
return complex(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real);
}
complex operator*(const double& x, const complex& c) {
return complex(x * c.real, x * c.imag);
}
complex operator*(const complex& c, const double& x) {
return x * c;
}
complex complex::operator~() const {
return complex(real, -imag);
}
int main() {
complex a(3, 4);
complex c;
cout << "Enter a complex number (q to quit):" << endl;
while (cin >> c) {
cout << "c is " << c << endl;
cout << "complex conjugate is " << ~c << endl;
cout << "a is " << a << endl;
cout << "a c is " << a * c << endl;
cout << "a-c is " << a - c << endl;
cout << "a*c is " << a * c << endl;
cout << "2*c is " << 2 * c << endl;
cout << "Enter a complex number (q to quit):" << endl;
}
cout << "Done!" << endl;
return 0;
}
阅读全文