eve*_*veo 17 c++ floating-point cout
如何在C++中格式化浮点数以输出四舍五入的小数位?我有没有运气setw
,并setprecision
为我的编译器只是告诉我,他们是not defined
.
cout << "Total : " << setw(2) << total << endl;
总产出: Total : 12.3961
我希望它是:12.40
或者12.39
如果要完成这项工作太多了.
bil*_*llz 17
您需要包含<iomanip>
并提供命名空间范围setw and setprecision
#include <iomanip>
std::setw(2)
std::setprecision(5)
Run Code Online (Sandbox Code Playgroud)
尝试:
cout.precision(5);
cout << "Total : " << setw(4) << floor(total*100)/100 << endl;
Run Code Online (Sandbox Code Playgroud)
要么
cout << "Total : " << setw(4) << ceil(total*10)/10 << endl;
Run Code Online (Sandbox Code Playgroud)
iostream提供精确功能,但要使用setw,您可能需要包含额外的头文件.
Jon*_*cer 17
使用cout << fixed
或cout.setf(ios::fixed)
,std::cout.precision(<# of decimal digits>)
如下所示(使用OSX Mavericks附带的Clang-503.0.40编译器):
#include <iostream>
int main()
{
using namespace std;
float loge = 2.718;
double fake = 1234567.818;
cout << fixed;
cout.precision(2);
cout << "loge(2) = " << loge << endl;
cout << "fake(2) = " << fake << endl;
cout.precision(3);
cout << "loge(3) = " << loge << endl;
cout << "fake(3) = " << fake << endl;
}
Run Code Online (Sandbox Code Playgroud)
这个输出是(注意四舍五入):
loge(2) = 2.72
fake(2) = 1234567.82
loge(3) = 2.718
fake(3) = 1234567.818
Run Code Online (Sandbox Code Playgroud)
这是简单的版本.代替使用cout << fixed;
,你可以使用cout.setf(ios::fixed);
(用于显示科学记数法,用科学替换固定 ;两者都将设置小数点右边的位数).请注意,如果格式标志不包含fixed或scientific,则cout.precision()也用于设置小数点两侧的总计显示的位数.互联网上有这方面的教程.
lee*_*mes 13
要包括尾随零,仅设置精度是不够的.您还必须将浮点格式更改为固定格式,它使用小数点后面的位数setprecision
来表示的位数:
std::cout << std::fixed << std::setprecision(2) << v;
Run Code Online (Sandbox Code Playgroud)
您可以使用 C++20 来做到这一点std::format
:
std::cout << std::format("Total : {:.2f}\n", total);
Run Code Online (Sandbox Code Playgroud)
或fmt::format
来自{fmt} 库的函数,std::format
基于。{fmt} 还提供了print
集成格式化和输出的功能,使其更加简单和高效(godbolt):
#include <fmt/core.h>
int main() {
fmt::print("Total : {:.2f}\n", 12.3961);
}
Run Code Online (Sandbox Code Playgroud)
输出:
Total : 12.40
Run Code Online (Sandbox Code Playgroud)
这使用 IEEE754 默认舍入模式(舍入到最接近的偶数),因此您必须自行舍入(How do I round up/down adecimal place of a float value? C++)。
如果您想要四舍五入的尾随零,您可以使用 C 函数printf
。
#include <iostream>
#include <cstdio>
int main() {
float v = 12.3961;
std::printf("%.2f",v); //prints 12.40
}
Run Code Online (Sandbox Code Playgroud)
相比:
#include <iostream>
#include <iomanip>
int main() {
float v = 12.3961;
std::cout << std::setprecision(4) << v; //prints 12.4
}
Run Code Online (Sandbox Code Playgroud)