首页 > 解决方案 > 如何根据用户输入的浮点数编写“if”语句?

问题描述

我正在尝试获取用户的输入并做出条件声明,即如果用户输入的浮点数包含 0.1,0.2,0.3,0.4,则将其向上舍入,否则将其向下舍入。我知道只需使用该round()功能即可解决此问题,但我想使用math.ceil()and math.floor()。到目前为止我只有这么多,我确信这是错误的。

import math

while 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)

标签: python

解决方案


你可以这样检查:

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)

推荐阅读