C ++中的浮点格式 [英] Float formatting in C++
本文介绍了C ++中的浮点格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C ++中格式化浮点数以输出到小数点后两位?我在 setw
和 setprecision
上没有运气,因为我的编译器告诉我它们是未定义
。
How do you format a float in C++ to output to two decimal places rounded up? I'm having no luck with setw
and setprecision
as my compiler just tells me they are not defined
.
cout<< 总计:<< setw(2)<<总计<< endl;
总输出:总计:12.3961
我希望它是: 12.40
或 12.39
(如果工作量过多)
I'd like it to be: 12.40
or 12.39
if it's too much work to round up.
推荐答案
您需要包括< iomanip>
并将名称空间范围提供给 setw和setprecision
You need to include <iomanip>
and provide namespace scope to setw and setprecision
#include <iomanip>
std::setw(2)
std::setprecision(5)
尝试:
cout.precision(5);
cout << "Total : " << setw(4) << floor(total*100)/100 << endl;
或
cout << "Total : " << setw(4) << ceil(total*10)/10 << endl;
iostream提供了精确功能,但是要使用setw,可能需要包括额外的头文件。
iostream provides precision function, but to use setw, you may need to include extra header file.
这篇关于C ++中的浮点格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文