C++中的浮點數精度是什麼?
在 C++ 中,浮點數的大小為 4 位元組或 8 位元組。它可以儲存幾個小數位。例如,1/3 = 0.333333……直至無窮大。如果將其儲存在浮點型變數中,它將儲存一些有效數字。預設值為 6。因此,C++ 中的浮點數通常可以顯示 6 位小數。
我們可以使用 setprecision 更改精度的 size。這存在於 iomanip 標頭檔案中。我們看一個例子來了解一下。
示例程式碼
#include <iostream> #include <iomanip> using namespace std; int main() { double x = 2.3654789d; cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl; cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl; cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl; }
輸出
Print up to 3 decimal places: 2.365 Print up to 2 decimal places: 2.37 Print up to 7 decimal places: 2.3654789
廣告