← 從零開始學 Python 第 52 課,共 78 課 · 10 XP

math 模組

理論與題目說明

機器翻譯,尚未經母語人士審閱。

math 提供一般運算子沒有的數學功能:

import math

math.sqrt(25)        # 5.0  —— 平方根
math.pi              # 3.141592653589793
math.ceil(2.1)       # 3    —— 無條件進位
math.floor(2.9)      # 2    —— 無條件捨去
math.gcd(12, 18)     # 6    —— 最大公因數
math.hypot(3, 4)     # 5.0  —— 斜邊
math.factorial(5)    # 120

別把 round()、math.floor() 和 int() 搞混:

2.7 -2.7
round(x) 3 -3
math.floor(x) 2 -3
int(x) 2 -2

日常的問題常常需要 math.ceil:一台巴士有 20 個座位,45 個人需要幾台巴士?math.ceil(45 / 20) = 3。

題目。 讀入學生人數和一台巴士的座位數。顯示需要幾台巴士。

免費註冊,就能直接在瀏覽器裡解這道題:程式碼編輯器、執行、測試檢查和提示。