实现两个复数的四则运算。
r1为第一个操作数的实部,i1为第一个操作数的虚部,op为操作符,r2为第二个操作数的实部,i2为第二个操作数的虚部。
输出两个复数的运算结果。
如果op为'+' '-' '*' '/'以外的字符,输出:"error" 。op为'/',且r2,i2均为0时,输出:"Divisor cannot be 0"。(不带引号)
不会啊,难啊
r1为第一个操作数的实部,i1为第一个操作数的虚部,op为操作符,r2为第二个操作数的实部,i2为第二个操作数的虚部。
输出两个复数的运算结果。
如果op为'+' '-' '*' '/'以外的字符,输出:"error" 。op为'/',且r2,i2均为0时,输出:"Divisor cannot be 0"。(不带引号)
不会啊,难啊
我之前学C++基础的时候写过差不多的,基本考察的就是运算符的重载(在类中),我把代码贴上来,你看着改。
#include<iostream>
#include<iomanip>
#include<string>
using std::cin;
using std::cout;
using std::fixed;
using std::endl;
using std::setprecision;
using std::string;
class plural
{
public:
plural(double a = 0.0, double b = 0.0);
void show();
void operator_show(double x, double y);
void operator +(plural m);
void operator -(plural m);
void operator *(plural m);
void operator /(plural m);
private:
double a{ 0.0 };
double b{ 0.0 };
};
plural::plural(double a, double b)
{
this->a = a;
this->b = b;
}
void plural::show()
{
if (b >= 0)
cout << fixed << setprecision(1) << '(' << a << '+' << b << "i)";
else
cout << fixed << setprecision(1) << '(' << a << b << "i)";
}
void plural::operator_show(double x, double y)
{
if ((-0.1 < x&&x < 0.1) && !(-0.1 < y&&y < 0.1))
{
cout << fixed << setprecision(1) << y << 'i';
}
else if (!(-0.1 < x&&x < 0.1) && (-0.1 < y&&y < 0.1))
{
cout << fixed << setprecision(1) << x;
}
else if ((-0.1 < x&&x < 0.1) && (-0.1 < y&&y < 0.1))
{
cout << 0.0;
}
else if (y >= 0.1)
cout << fixed << setprecision(1) << x << '+' << y << 'i';
else
cout << fixed << setprecision(1) << x << y << 'i';
}
void plural::operator +(plural m)
{
double x = a + m.a;
double y = b + m.b;
this->show();
cout << " + ";
m.show();
cout << " = ";
operator_show(x, y);
}
void plural::operator -(plural m)
{
double x = a - m.a;
double y = b - m.b;
this->show();
cout << " - ";
m.show();
cout << " = ";
operator_show(x, y);
}
void plural::operator *(plural m)
{
double x = a * m.a - b * m.b;
double y = a * m.b + b * m.a;
this->show();
cout << " * ";
m.show();
cout << " = ";
operator_show(x, y);
}
void plural::operator /(plural m)
{
double x = (a * m.a + b * m.b) / (m.a*m.a + m.b*m.b);
double y = (b * m.a - a * m.b) / (m.a*m.a + m.b*m.b);
this->show();
cout << " / ";
m.show();
cout << " = ";
operator_show(x, y);
}
int main()
{
double a1, b1, a2, b2;
cin >> a1 >> b1 >> a2 >> b2;
plural p1{ a1,b1 };
plural p2{ a2,b2 };
p1 + p2;
cout << endl;
p1 - p2;
cout << endl;
p1*p2;
cout << endl;
p1 / p2;
}