我想我会创建一个小类(或结构)来保存输出中的每个项目,并处理项目的格式:
struct item {
std::string label;
double amount;
std::string note;
friend std::ostream &operator<<(std::ostream &os, item const &i) {
os << std::setprecision(2) << std::fixed;
os << std::setw(15) << std::left << i.label
<< " $" << std::right << std::setw(8) << i.amount;
if (!i.note.empty())
os << " (" << i.note << ")";
return os;
}
};
有了这些,只需按照正确的顺序创建项目,然后将它们写出来:
std::vector<item> items {
{ "Sub-total:", 17530},
{ "+ Sales Tax:", 1139},
{ "- Discount:", 25},
{ "+ Shipping:", 0, "Ship to: NJ"},
{ "= Total:", 18644.44}
};
for (auto const & i : items)
std::cout << i << "\n";
然而,实际上,您通常会从一些实际物品(客户购买的东西)开始,所有这些物品都是从客户购买的东西中计算出来的:
class sale {
std::vector<item> items;
const double tax_rate;
public:
sale(std::initializer_list<item> const& i, double tax_rate = 0.065)
: items(i)
, tax_rate(tax_rate)
{}
friend std::ostream& operator<<(std::ostream& os, sale const& s) {
item subtotal{ "Subtotal:", 0 };
item discount{ "- Discount: ", 0 };
item sales_tax{ "+ Sales Tax:", 0 };
item shipping{ "+ Shipping:", 0, 0, "Shipping to: NJ" };
item total{ "= Total:", 0 };
for (auto const& i : s.items) {
os << i << "\n";
subtotal.amount += i.amount;
discount.amount += i.discount;
shipping.amount += i.shipping;
total.amount += i.amount;
total.amount -= i.discount;
total.amount += i.shipping;
}
sales_tax.amount = subtotal.amount * s.tax_rate;
os << std::string(40, '-') << '\n';
os << subtotal << '\n';
os << sales_tax << '\n';
os << discount << '\n';
os << shipping << '\n';
os << total << '\n';
return os;
}
};
这样,我们只需列出他们购买的商品,它就会计算小计、税金等。
int main() {
sale items {
{"Kia Rio", 15390.00, 25},
{"Stereo", 135.95},
{"Undercoating", 249.95},
{"Mud flaps", 124.99},
{ "ADP", 375.25}
};
std::cout << items << "\n";
}
...产生类似这样的输出:
Kia Rio $15390.00
Stereo $ 135.95
Undercoating $ 249.95
Mud flaps $ 124.99
ADP $ 375.25
------------------------------
Subtotal: $16276.14
+ Sales Tax: $ 1057.95
- Discount: $ 25.00
+ Shipping: $ 0.00 (Shipping to: NJ)
= Total: $16251.14