gpt4 book ai didi

C++货币输出

转载 作者:太空狗 更新时间:2023-10-29 23:24:08 26 4
gpt4 key购买 nike

我现在正在学习 C++ 类(class),并且已经完成了我的期末作业。然而有一件事困扰着我:

虽然我有针对特定输出的测试的正确输出,basepay 应该是 133.20 并且显示为 133.2。有没有办法让它显示额外的 0 而不是将其关闭?

有人知道这是否可行以及如何实现吗?提前谢谢你

我的代码如下:

cout<< "Base Pay .................. = " << basepay << endl;
cout<< "Hours in Overtime ......... = " << overtime_hours << endl;
cout<< "Overtime Pay Amount........ = " << overtime_extra << endl;
cout<< "Total Pay ................. = " << iIndividualSalary << endl;
cout<< endl;

cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%% EMPLOYEE SUMMARY DATA%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%% Total Employee Salaries ..... = " << iTotal_salaries <<endl;
cout<< "%%%% Total Employee Hours ........ = " << iTotal_hours <<endl;
cout<< "%%%% Total Overtime Hours......... = " << iTotal_OvertimeHours <<endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;

最佳答案

如果你想用 C++ 的方式来做,并且你可以用 C++11 标志编译,你可以使用标准库:

// Note: the value in cents!
const int basepay = 10000;

// Create a stream and imbue it with the local configuration.
std::stringstream ss;
ss.imbue(std::locale(""));

// The stream contains $100.00 (assuming a en_US locale config)
ss << std::showbase << std::put_money(basepay);

示例 here .

这种方法有什么优势?

  • 它使用本地配置,因此输出在任何机器上都是一致的,即使是小数点分隔符、千位分隔符、货币符号和小数点精度(如果需要)也是如此。
  • 所有的格式化工作已经由 std 库完成,要做的工作更少!

关于C++货币输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15327706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com