【问题描述】
设计一个复数类并实现复数的三种运算。
设计一个复数类( Complex ),该类有两个成员变量和两个函数(成员变量访问性为私有,函数为公有),并重载+,-,*运算符,实现复数的加、减、乘运算,具体要求如下:
成员变量:float real,代表实部。
成员变量:float image,代表虚部。
构造函数:Complex(float r,float i),用两个参数设置 real 和 image 成员变量的值。
输出复数函数:void Print(),输出格式为:实部 +/- 虚部i,比如1+1i,0−5i。
【样例输入】
1 1 2 2(数据分为两组,前两个和后两个数分别表示一个复数 c1 和 c2,即c1=1+1i,c2=2+2i)
【样例输出】
-
c1 = 1+1i
-
c2 = 2+2i
-
c1 + c2 = 3+3i
-
c1 - c2 = -1-1i
-
c1 * c2 = 0+4i
#include <iostream>
using namespace std;
class Complex{
private:
float real;
float image;
public:
Complex(float r=0.0,float i=0.0);
void Print();
Complex operator+(Complex c);
Complex operator-(Complex c);
Complex operator*(Complex c);
};
Complex::Complex(float r,float i)
{
real=r;
image=i;
}
void Complex::Print()
{
cout<<real;
if(image>=0)
cout<<"+";
cout<<image<<"i"<<endl;
}
Complex Complex::operator+(Complex c)
{
Complex temp;
temp.real=real+c.real;
temp.image=image+c.image;
return temp;
}
Complex Complex::operator-(Complex c)
{
Complex temp;
temp.real=real-c.real;
temp.image=image-c.image;
return temp;
}
Complex Complex::operator*(Complex c)
{
Complex temp;
temp.real=real*c.real-image*c.image;
temp.image=real*c.image+image*c.real;
return temp;
}
int main()
{
float a,b,c,d;
cin >> a >> b >> c >> d;
Complex c1(a,b),c2(c,d);
cout << "c1 = ";
c1.Print();
cout << "c2 = ";
c2.Print();
cout << "c1 + c2 = ";
(c1 + c2).Print();
cout << "c1 - c2 = ";
(c1 - c2).Print();
cout << "c1 * c2 = ";
(c1 * c2).Print();
return 0;
}
【注】此分栏为西安理工大学C++练习题,所有答案仅供同学们参考。