C ++浮点格式 [英] C++ float formatting

查看:101
本文介绍了C ++浮点格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何格式化C ++中的浮点数以输出到小数点后两位?我没有运气与 setw setprecision ,因为我的编译器只是告诉我他们是未定义



cout< Total:<< setw(2)<<总< endl;



总输出:总计:12.3961



我想要的是: 12.40 12.39 如果工作太多

解决方案

您需要包括< iomanip> 并为 setw和setprecision提供命名空间范围

  #include< iomanip> ; 
std :: setw(2)
std :: setprecision(5)

try:

  cout.precision(5) 
cout<< Total:<< setw(4)<< floor(total * 100)/ 100 < endl;

  cout<< Total:<< setw(4)<<细胞(总* 10)/ 10 < endl; 

iostream提供了精确的函数,但是要使用setw,你可能需要包含额外的头文件。 p>

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 << "Total : " << setw(2) << total << endl;

total outputs: Total : 12.3961

I'd like it to be: 12.40 or 12.39 if it's too much work to round up.

解决方案

You need to include <iomanip> and provide namespace scope to setw and setprecision

#include <iomanip>
std::setw(2)
std::setprecision(5)

try:

cout.precision(5);
cout << "Total : " << setw(4)   << floor(total*100)/100 << endl;

or

 cout << "Total : " << setw(4)   << ceil(total*10)/10 << endl;

iostream provides precision function, but to use setw, you may need to include extra header file.

这篇关于C ++浮点格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆