如何格式化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