如何格式化C++中的浮点数以输出到小数点后两位?我没有setw
和setprecision
的运气,因为我的编译器告诉我他们是not defined
。C++浮点格式化
cout << "Total : " << setw(2) << total << endl;
总产出:Total : 12.3961
我想它是:12.40
或12.39
,如果它太辛苦了围捕。
如何格式化C++中的浮点数以输出到小数点后两位?我没有setw
和setprecision
的运气,因为我的编译器告诉我他们是not defined
。C++浮点格式化
cout << "Total : " << setw(2) << total << endl;
总产出:Total : 12.3961
我想它是:12.40
或12.39
,如果它太辛苦了围捕。
您需要包括<iomanip>
并提供命名空间范围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提供精确的功能,但运输及工务局局长用,你可能需要包含额外的头文件。
如果您希望四舍五入后的零,您可以使用C函数printf
。
#include <iostream>
#include <cstdio>
int main() {
float v = 12.3961;
std::printf("%.2f",v); //prints 12.40
}
相比:
#include <iostream>
#include <iomanip>
int main() {
float v = 12.3961;
std::cout << std::setprecision(4) << v; //prints 12.4
}
也包括尾随零,这是不够的设置精度。您还可以浮点格式更改为固定格式,它采用的位数为小数点后setprecision
告诉作为数字数量:
std::cout << std::fixed << std::setprecision(2) << v;
要使用此功能,您需要将其添加到您的包括: #include
使用cout << fixed
或cout.setf(ios::fixed)
和std::cout.precision(<# of decimal digits>)
(如使用OSX Mavericks附带的Clang-503.0.40编译器):
#include <iostream>
using namespace std; // Hopefully this doesn't offend purists :-)
// I just want to demonstrate usage with the
// fewest keystrokes and the clearest format
int main()
{
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;
}
从这个输出(注意四舍五入):
loge(2) = 2.72
fake(2) = 1234567.82
loge(3) = 2.718
fake(3) = 1234567.818
这是一个简单的版本。代替使用cout << fixed;
,您可以使用cout.setf(ios::fixed);
(用于显示科学记数法,用固定替换为科学;二者都将数字设置为小数点右侧)。请注意,如果格式标志不包含固定的或科学,cout.precision()也用于设置小数点两侧总显示的位数。在互联网上有这个教程。
向我们显示代码。 – 0x499602D2
我的不好,忘了它并编辑它。 – eveo