2013-01-21 68 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()也用於設置小數點兩側總顯示的位數。在互聯網上有這個教程。