4

我现在正在学习 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;
4

6 回答 6

11

如果您想以 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);

这里的例子。

这种方法有什么优点?

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

使用cout.precision设置精度,并使用fixed切换定点模式:

cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;
于 2013-03-10T21:18:05.580 回答
5

是的,这可以使用流操作符来实现。例如,将输出设置为固定浮点表示法,定义精度(在您的情况下为 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);
}

希望能帮助到你。祝你好运!

于 2013-03-10T21:20:02.040 回答
1

您可以更改cout属性:

cout.setf(ios::fixed);
cout.precision(2);`

现在cout << 133.2;将打印133.20

于 2013-03-10T21:19:41.867 回答
1

看一下这个:

int main()
{
    double a = 133.2;

    cout << fixed << setprecision(2) << a << endl;
}

输出

133.20

于 2013-03-10T21:19:59.327 回答
1

你需要看看precisionfixed

#include <iostream>

int main()
{
    double f = 133.20;

    // default
    std::cout << f << std::endl;

    // precision and fixed-point specified
    std::cout.precision(2);
    std::cout << std::fixed << f << std::endl;

    return 0;
}
于 2013-03-10T21:23:56.440 回答