#include<iostream>
#include<math.h>
#include<string>
#include<stdlib.h>
using namespace std;
class Complex
{
public:
Complex() {}
Complex(const Complex& c) {
real = c.real;
image = c.image;
name = c.name;
}
Complex(float r, float i,string name)
{
real = r;
image = i;
this->name = name;
}
void Print()
{
if (this->image >= 0)
{
cout << real << " + " << image << "i\n";
}
else
{
cout << real << " - " << abs(image) << "i\n";
}
}
Complex operator+(Complex& r)
{
Complex c;
c.real = this->real + r.real;
c.image = this->image + r.image;
return c;
}
Complex operator-(Complex& r)
{
Complex c;
c.real = this->real - r.real;
c.image = this->image - r.image;
return c;
}
Complex operator*(Complex& r)
{
Complex c;
c.real = (this->real * r.real) - (this->image * r.image);
c.image = (this->image * r.real) + (this->real * r.image);
return c;
}
Complex operator/(Complex& r)
{
Complex c;
c.real = (real * r.real + image * r.image) / (r.image * r.real + r.image * r.image);
c.image = (image * r.real + real * r.image) / (r.real * r.real + r.image * r.image);
return c;
}
private:
float real;
float image;
string name;
};
int flag = 1;
void is_continue();
int main()
{
float real = 0, image = 0;
cout << "\t欢迎使用复数计算器\n\n";
cout << "\t请输入第一个复数的实部和虚部(用空格分割)\n";
cin >> real >> image;
Complex complex_1(real, image, "c1");
cout << "c1 = ";
complex_1.Print();
cout << "\n";
cout << "\t请输入第二个复数的实部和虚部(用空格分割)\n";
cin >> real >> image;
Complex complex_2(real, image, "c2");
cout << "c2 = ";
complex_2.Print();
cout << "\n";
cout << "****************************************************\n\n";
cout << "\t\t菜单\n";
cout << "+\t2个复数相加\n\n";
cout << "-\t2个复数相减\n\n";
cout << "*\t2个复数相乘\n\n";
cout << "/\t2个复数相除\n\n";
cout << "****************************************************\n\n";
char oper = 0;
char c;
while (flag)
{
cout << "\n请选择你要进行的操作\n";
cin >> oper;
while ((c = getchar()) != '\n');
Complex ans;
switch (oper)
{
case '+':
ans = complex_1 + complex_2;
cout << "c1 + c2 =";
ans.Print();
cout << "\n";
is_continue();
break;
case '-':
ans = complex_1 - complex_2;
cout << "c1 -c2 =";
ans.Print();
cout << "\n";
is_continue();
break;
case '*':
ans = complex_1 * complex_2;
cout << "c1 * c2 =";
ans.Print();
cout << "\n";
is_continue();
break;
case '/':
ans = complex_1 / complex_2;
cout << "c1 / c2 =";
ans.Print();
cout << "\n";
is_continue();
break;
default:
cout << "请输入有效操作符:\n";
break;
}
if (flag == 0)
{
system("cls");
cout << "****************************************************\n\n";
cout << "\t\t欢迎下次使用\n\n";
cout << "****************************************************\n\n";
break;
}
}
}
void is_continue()
{
string choose = "";
cout << "是否要进行别的操作?yes/no :\n";
while (1)
{
cin >> choose;
if (choose == "yes")
{
flag = 1;
break;
}
else if (choose == "no")
{
flag = 0;
break;
}
else {
cout << "\t请输入有效选择\n";
}
}
}
有帮助的话点个攒哇👍
|