開始使用免費開始

列印浮點數

科學記號是一種很有用的數字表示方式,但在列印浮點數時可能不好讀。不過,你可以用先前學過的 f 字串,加上格式化指定詞,讓輸出每次都正確。舉例來說,若要在 f 字串中把變數格式化為浮點數,可以使用 f 格式化指定詞,例如:print(f"{some_variable:f}")。你也可以在浮點數的格式化指定詞上設定小數精確度,例如 print(f"{some_variable:.4f}") 會列印到小數點後 4 位。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • 列印 float1float2float3,留意何時會跳到科學記號。
  • 使用預設的浮點數格式化指定詞列印 float2float3,觀察 float3 發生了什麼變化。
  • float3 以浮點數格式化指定詞並設定精確度為 7 來列印。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Print floats 1, 2, and 3
print(____)
print(____)
print(____)

# Print floats 2 and 3 using the f string formatter
print(f"{____}")
print(f"{____}")

# Print float 3 with a 7 f string precision
print(f"{____}")
編輯並執行程式碼