关于复数的常见操作:
1. 创建复数
2. 取实部
3. 取虚部
4. 两个复数相加
5. 两个复数相减
0. 退出
#include<iostream>
using namespace std;
int choose = -1;
float x, y, x1, y11, x2, y2;
//Complex C, C1, C2, C3;
typedef struct Complex
{
float x; //实部
float y; //虚部
}Complex;
//1.构造一个复数
Complex Creat(float x, float y)
{
Complex C;
C.x = x;
C.y = y;
return C;
};
//2.取复数C=x+yi的实部
float GetReal(Complex C)
{
float x1 = C.x;
return x1;
}
//3.取复数C=x+yi的虚部
float GetImag(Complex C)
{
float y11 = C.y;
return y11;
}
//4.求两个复数C1和C2之和sum
Complex Add(Complex C1, Complex C2)
{
Complex C;
C.x = C1.x + C2.x;
C.y = C1.y + C2.y;
return C;
}
//5.求两个复数C1和C2的差difference
Complex Sub(Complex C1, Complex C2)
{
Complex C;
C.x = C1.x - C2.x;
C.y = C1.y - C2.y;
return C;
}
//显示菜单
void show()
{
cout << "************************************" << endl;
cout << "*** 1. 创建复数 *****" << endl;
cout << "*** 2. 取实部 *****" << endl;
cout << "*** 3. 取虚部 *****" << endl;
cout << "*** 4. 两个复数相加 *****" << endl;
cout << "*** 5. 两个复数相减 *****" << endl;
cout << "*** 0. 退出 *****" << endl;
cout << "************************************" << endl;
}
//显示复数
void showComplex(Complex C)
{
if (C.y > 0)
{
cout << "复数为:" << C.x << "+" << C.y << "i" << endl;
}
else if (C.y < 0)
{
cout << "复数为:" << C.x << C.y << "i" << endl;
}
else
{
cout << "复数为:" << C.x << endl;
}
}
void main()
{
while (choose != -2)
{
show(); //输出菜单
cout << "请选择您要进行的操作" << endl;
cin >> choose; //获取要操作的选项
switch (choose)
{
case 1: //1.构造一个复数
{
cout << "请分别输入要构造的复数的实部和虚部:" << endl;
cin >> x1 >> y11;
Complex C = Creat(x1, y11);
cout << "您构造的";
showComplex(C);
break;
}
case 2: //取复数C = x + yi的实部
{
cout << "请分别输入要构造的复数的实部和虚部:" << endl;
cin >> x1 >> y11;
Complex C = Creat(x1, y11);
cout << "您构造的复数的实部为:" << GetReal(C) << endl;
break;
}
case 3: //取复数C=x+yi的虚部
{
cout << "请分别输入要构造的复数的实部和虚部:" << endl;
cin >> x1 >> y11;
Complex C = Creat(x1, y11);
cout << "您构造的复数的虚部为:" << GetImag(C) << endl;
break;
}
case 4: //求两个复数C1和C2之和sum
{
cout << "请分别输入第一个复数的实部和虚部:" << endl;
cin >> x1 >> y11;
Complex C1 = Creat(x1, y11);
cout << "您构造的第一个";
showComplex(C1);
cout << "请分别输入第二个复数的实部和虚部:" << endl;
cin >> x2 >> y2;
Complex C2 = Creat(x2, y2);
cout << "您构造的第二个";
showComplex(C2);
Complex C3 = Add(C1, C2);
cout << "两个复数的和的";
showComplex(C3);
break;
}
case 5: //求两个复数C1和C2的差difference
{
cout << "请分别输入第一个复数的实部和虚部:" << endl;
cin >> x1 >> y11;
Complex C1 = Creat(x1, y11);
cout << "您构造的第一个";
showComplex(C1);
cout << "请分别输入第二个复数的实部和虚部:" << endl;
cin >> x2 >> y2;
Complex C2 = Creat(x2, y2);
cout << "您构造的第二个";
showComplex(C2);
Complex C3 = Sub(C1, C2);
cout << "两个复数的差的";
showComplex(C3);
break;
}
case 0: //退出
{
system("cls");
cout << "已退出,欢迎再次使用" << endl;
choose = -2; //改变choose的值,退出并不在进行循环
break;
}
default:
cout << "您输入的选项不在可操作范围内,请重新输入!" << endl;
break;
}
}
system("pause");
}
运行结果截图