我試圖獲取用戶的輸入并做出一個條件語句,如果用戶輸入的浮點數包含 0.1,0.2,0.3,0.4,則將其向上舍入,如果不包含,則將其向下舍入。我知道只需使用該round()函數即可解決此問題,但我想使用math.ceil()and math.floor()。到目前為止我只有這么多,我確信這是錯誤的。import mathwhile True: x = float(input('Type something: ')) if x in (0.1,0.2,0.3,0.4): math.floor(x) print(x) else: math.ceil(x) print(x)
2 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
你可以這樣檢查:
while True:
x = float(input('Type something: '))
if x - math.floor(x)<0.5:
x = math.floor(x)
print(x)
else:
x = math.ceil(x)
print(x)

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
你必須重新定義x,x = math.ceil(x)
代碼:
import math
while True:
x = float(input('Type something: '))
if x-int(x) < 0.5:
x = math.floor(x)
print(x)
else:
x = math.ceil(x)
print(x)
添加回答
舉報
0/150
提交
取消