<font size = "6">:book: fixed & setprecision 用法說明與注意事項</font> [toc] :::success precision (n.) 精確 ::: setprecision 顧名思義就是設定精確度的意思, 而 fixed 搭配 setprecision 使用可以有不同的表示方式。 ## :books: fixed 是什麼? fixed是 輸出格式控制符(manipulator), 讓科學記號表示使用小數輸出。 ```cpp cout << 1e8; // 1e+08 cout << fixed << 1e8; // 100000000.000000 ``` :::warning 特別注意, `fixed` 會影響後續所有輸出。 ::: ### 怎麼取消 fixed 的後續影響?( C++11後 ) 可以使用 `defaultfloat` 來讓輸出回到預設狀態。 -> ==cout << defaultfloat== ```cpp cout << fixed << 1e8 << endl; // 100000000.000000 cout << 2.5e8 << endl; // 影響後續輸出 250000000.000000 cout << defaultfloat; // 回到預設狀態 cout << 1e8 << endl; // 1e+08 ``` ## :books: setprecision 是什麼? :::warning 需要使用 header `#include <iomanip>` 。 ::: `setprecision(n)` 用來控制精度,但意義會依有沒有 `fixed` 而不同。 ### ❌ 沒有使用fixed 會保留==小數點前最左邊開始計算 n 位==的部分。 ```cpp cout << setprecision(3) << 12.3456789 << endl; // 12.3 cout << setprecision(3) << 123.456789 << endl; // 123 cout << setprecision(3) << 1234.56789 << endl; // 1.23e+03 ``` :::warning 若小數點前超過位數表示則自動切換為科學記號表示, 反之則直接表示。 ::: ### ✔️ 有使用fixed 會保留==小數點後開始計算==的位數,並在小數點後 n+1 位做四捨五入(缺項補0)。 ```cpp cout << fixed << setprecision(3) << 12.3456789 << endl; // 12.346(5進位) cout << setprecision(3) << 12.3454789 << endl; // 12.345(4捨去) cout << setprecision(3) << 1234.5 << endl; // 1234.500(缺項補0) ``` :::info 若要印整數可以 `setprecision(0)` 。 :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up