题目描述
定义一个人民币类,包括元、角、分三个非负整数属性
请根据以下类声明与主函数,完成以下类实现填空
由于OJ编译器对double强制类型转换成int的处理精度有偏差,建议加0.005处理(例如数据1.38,由于误差,在内存中的存储值为1.379999)
输入
第一行输入t,表示有t个测试实例
每个实例包含两行输入:
第1行输入一个浮点数,表示以元为单位的人民币金额,例如输入1.23,对应人民币对象为1元2角3分
第2行输入三个整数,表示以元、角、分为参数的人民币金额,例如输入4 5 6,对应人民币对象为4元5角6分
输出
每个实例输出两行:
第1行输出两个人民币金额比较的结果,具体看样例
第2行输出两个人民币金额相加的结果,具体看样例
//
输入样例:
2
1.23
4 5 6
7.8
6 5 4
输出样例:
1yuan2jiao3fen <= 4yuan5jiao6fen
1yuan2jiao3fen + 4yuan5jiao6fen = 5yuan7jiao9fen
7yuan8jiao0fen > 6yuan5jiao4fen
7yuan8jiao0fen + 6yuan5jiao4fen = 14yuan3jiao4fen
AC代码:
#include <iostream>
using namespace std;
class RMB;
ostream &operator<<(ostream &, RMB &);
istream &operator>>(istream &, RMB &);
class RMB
{
protected:
int yuan, jiao, fen;
public:
RMB(double a = 0.0);
RMB(int, int, int);
bool operator>(RMB &);
friend ostream &operator<<(ostream &, RMB &); // 一行输出,无换行
friend istream &operator>>(istream &, RMB &);
friend RMB operator+(RMB &, RMB &);
};
// 完成以下类定义的填空
RMB::RMB(double a)
{
int totalFen = static_cast<int>((a + 0.005) * 100);
yuan = totalFen / 100;
jiao = (totalFen % 100) / 10;
fen = totalFen % 10;
}
RMB::RMB(int y, int j, int f)
{
yuan = y;
jiao = j;
fen = f;
}
bool RMB::operator>(RMB &other)
{
int totalFen1 = yuan * 100 + jiao * 10 + fen;
int totalFen2 = other.yuan * 100 + other.jiao * 10 + other.fen;
return totalFen1 > totalFen2;
}
ostream &operator<<(ostream &out, RMB &rmb)
{
out << rmb.yuan << "yuan" << rmb.jiao << "jiao" << rmb.fen << "fen";
return out;
}
istream &operator>>(istream &in, RMB &rmb)
{
in >> rmb.yuan >> rmb.jiao >> rmb.fen;
return in;
}
RMB operator+(RMB &r1, RMB &r2)
{
int totalFen1 = r1.yuan * 100 + r1.jiao * 10 + r1.fen;
int totalFen2 = r2.yuan * 100 + r2.jiao * 10 + r2.fen;
int totalFen = totalFen1 + totalFen2;
RMB result(totalFen / 100, (totalFen % 100) / 10, totalFen % 10);
return result;
}
// 主函数
int main()
{
int t;
double val_yuan;
cin >> t;
while (t--)
{
cin >> val_yuan; // 输入一个浮点数,例如1.23
RMB r1(val_yuan); // 例如上一行输入1.23,则生成对象r1是1元2角3分
RMB r2;
cin >> r2; // 输入一行三个整数参数,按元、角、分输入
if (r1 > r2)
cout << r1 << " > " << r2 << endl;
else
cout << r1 << " <= " << r2 << endl;
RMB r3 = r1 + r2;
cout << r1 << " + " << r2 << " = " << r3 << endl;
}
return 0;
}