python:round(),math.ceil(),math.floor()的區別

  • 2019 年 10 月 10 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/weixin_40313634/article/details/96450679

round(),math.ceil(),math.floor()的區別

    1. round():round 是「附近、周圍」的意思,所以該函數是一個求近似值的函數,用四捨五入法(有特例)。例子如下:
#  正數: 四捨五入  import math  round(11.46)    # 結果:11  round(11.56)    # 結果:12    # 負數: 取絕對值後四捨五入,再變回負數  round(-11.46)    # 結果:-11  round(-11.56)    # 結果:-12    # 小數部分是 .5 時需注意,結果取最接近的偶數(特例)  round(11.5)    # 結果:12  round(10.5)    # 結果:10  round(-11.5)    # 結果:-12  round(-10.5)    # 結果:-10
    1. math.ceil():ceil 是「天花板」的意思,所以該函數是求較大數的,用進一法。例子如下。
import math  # 如果小數部分非0, 則取整加1  math.ceil(11.46)    #  結果: 12  math.ceil(-11.46)    #  結果: -11
    1. math.floor():floor」有「地板」的意思,所以該函數是取較小數,和ceil函數相反。例子如下。
import math  math.floor(11.46)    #  結果: 11  math.floor(-11.46)    #  結果: -12