![](/img/trans.png)
[英]How does printf or iostream specify maximum number of digits after the point
[英]How can I limit the number of digits displayed by printf after the decimal point?
我寫了一個小程序,它使用scanf
讀取兩個整數,然后執行各種算術計算。 我正在使用printf
來顯示結果。 如何讓printf
只顯示小數點后兩位? 從簡化的代碼示例開始:
#include <stdio.h>
int main(void)
{
double third = 1.0 / 3.0;
// display data
printf("\n%20s%20s", "Description", "Data");
printf("\n%20s%20s", "-----------", "----");
printf("\n%20s%20lf", "One third", third);
printf("\n");
return 0;
}
這將打印“0.333333”作為third
值。 我將如何更改上述內容以獲得以下輸出?
\n 描述數據\n ----------- ----\n 三分之一 0.33\n
在你想要的地方使用“%.2f”。
比如修改下面的語句
printf("\n%20s%20lf", "Fraction", quotientdecimal);
進入這個:
printf("\n%20s%.2f", "Fraction", quotientdecimal);
將只顯示變量 quotlentdecimal 的兩個小數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.