c++货币输出
C++ currency output
我正在上一门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;
如果你想用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库完成,更少的工作要做!
使用cout。Precision为设定精度,fixed为切换定点模式:
cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;
是的,这可以使用流操纵符来实现。例如,将输出设置为固定的浮点表示法,定义精度(在您的示例中为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: %.02fn", px);
}
希望有帮助。好运!
看看这个:
int main()
{
double a = 133.2;
cout << fixed << setprecision(2) << a << endl;
}
输出133.20
您可以更改cout
属性:
cout.setf(ios::fixed);
cout.precision(2);`
现在cout << 133.2;
将打印133.20
你需要看一下精度和固定
#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;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- c++货币输出