在 C 中,要保留兩位小數輸出而不四捨五入,可以使用以下步驟:使用 std::fixed 將浮點數表示為固定小數位數。使用 std::setprecision() 設定要保留的小數位數,包括小數點。
如何保留C 中2 位小數輸出卻不四捨五入
在C 中,要保留2 位小數輸出而不四捨五入,可以使用std::fixed
和std::setprecision()
函數。
1. std::fixed
std::fixed
將浮點數表示為固定小數位數。預設情況下,浮點數以科學計數法表示,而 std::fixed
將其轉換成十進位表示法,並保留指定的位數。
2. std::setprecision()
#std::setprecision()
設定要保留的小數位數。對於浮點數,std::setprecision()
指定要顯示的小數位數,包括小數點。
範例程式碼:
#include <iostream> #include <iomanip> using namespace std; int main() { double value = 123.4567; // 保留 2 位小数输出而不四舍五入 cout << fixed << setprecision(2) << value << endl; return 0; }
輸出:
<code>123.45</code>
在這個範例中,std::fixed
將value
轉換為十進位表示法,而std::setprecision(2)
指定保留2 位小數。因此,輸出結果保留了 2 位小數而不四捨五入。
以上是c++中如何保留2位元小數輸出但不四捨五入的詳細內容。更多資訊請關注PHP中文網其他相關文章!