我正在参加C ++课程,并完成了我的最终作业。然而,有一件事让我烦恼:
虽然我对特定输出的测试有正确的输出,但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;
答案 0 :(得分:6)
如果你想用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。
这种方法有哪些优势?
答案 1 :(得分:5)
是的,这可以使用stream manipulators。例如,将输出设置为固定浮点表示法,定义精度(在您的情况下为2)并将填充字符定义为“0”:
#include <iostream>
#include <iomanip>
int main()
{
double px = 133.20;
std::cout << "Price: "
<< std::fixed << std::setprecision(2) << std::setfill('0')
<< px << std::endl;
}
如果你喜欢C风格的格式,这里有一个使用printf()
来实现同样的例子:
#include <cstdio>
int main()
{
double px = 133.20;
std::printf("Price: %.02f\n", px);
}
希望它有所帮助。祝你好运!
答案 2 :(得分:3)
使用cout.precision设置精度,fixed切换定点模式:
cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;
答案 3 :(得分:1)
您可以更改cout
属性:
cout.setf(ios::fixed);
cout.precision(2);`
现在cout << 133.2;
将打印133.20
答案 4 :(得分:1)
检查出来:
int main()
{
double a = 133.2;
cout << fixed << setprecision(2) << a << endl;
}
输出
133.20
答案 5 :(得分:1)