共計 458 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 的 round() 函數用于對浮點數進行四舍五入。
round() 函數的常見用法有:
- round(x):對 x 進行四舍五入,返回一個整數。
- round(x, n):對 x 進行四舍五入,保留 n 位小數。當 n 為正數時,小數點后保留 n 位小數;當 n 為負數時,整數部分保留 n 位小數。
- round(x, None):對 x 進行四舍五入,返回最接近的整數值。
- round(x, -n):對 x 進行四舍五入,返回一個整數,保留到最近的 10 的 n 次方。
以下是一些示例:
x = 3.14159
print(round(x)) # 輸出: 3
print(round(x, 2)) # 輸出: 3.14
print(round(x, -1)) # 輸出: 0
print(round(x, -2)) # 輸出: 0
print(round(4.5)) # 輸出: 4
print(round(4.5, 0)) # 輸出: 4
print(round(4.51)) # 輸出: 5
print(round(4.51, 1)) # 輸出: 4.5
注意:在使用 round() 函數時,需要注意浮點數的精度問題。
丸趣 TV 網 – 提供最優質的資源集合!
正文完