2013-01-21 67 views
11

如何格式化C++中的浮点数以输出到小数点后两位?我没有setwsetprecision的运气,因为我的编译器告诉我他们是not definedC++浮点格式化

cout << "Total : " << setw(2) << total << endl;

总产出:Total : 12.3961

我想它是:12.4012.39,如果它太辛苦了围捕。

+1

向我们显示代码。 – 0x499602D2

+0

我的不好,忘了它并编辑它。 – eveo

回答

12

您需要包括<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提供精确的功能,但运输及工务局局长用,你可能需要包含额外的头文件。

+0

没有其他方式来格式化它,而不包括其他库?我问这个是因为我的教授是超级严格的,我假设他不希望我们去探索更多的图书馆,而不是我们在课堂上学过的'iostream'和'cstring'。 – eveo

+0

'setprecision(2)'显示'12'而不是'12.39'。如何显示小数? – eveo

+0

@eveo''是C++标准库的一部分。一位好的教授不应该禁止你探索互联网寻找好的解决方案。如果你可以解释为什么你包含另一个*标准库文件*(它不是另一个*库*),它应该是非常好的。 – leemes

2

如果您希望四舍五入后的零,您可以使用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 
} 
+0

这不回答问题,是吗? – leemes

+0

@leemes他问如何获得格式化精度输出。他不是吗?至少这是我读的。 – Rapptz

+0

嗯...我认为这是我的错误。你的回答是正确的。但是,我不喜欢你想回退到像'printf'这样的C函数。而你的C++解决方案不会按照他所希望的那样打印正确的输出(尾随0)。 [顺便说一下:你说的是领先而不是拖尾] – leemes

8

也包括尾随零,这是不够的设置精度。您还可以浮点格式更改为固定格式,它采用的位数为小数点后setprecision告诉作为数字数量:

std::cout << std::fixed << std::setprecision(2) << v; 

Working online example code

+3

要使用此功能,您需要将其添加到您的包括: #include Allen

12

使用cout << fixedcout.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()也用于设置小数点两侧总显示的位数。在互联网上有这个教程。