如何根据用户输入的浮点数编写“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)


月关宝盒
浏览 120回答 2
2回答

扬帆大鱼

你可以这样检查:while True:&nbsp; &nbsp; x = float(input('Type something: '))&nbsp; &nbsp; if x - math.floor(x)<0.5:&nbsp; &nbsp; &nbsp; &nbsp; x = math.floor(x)&nbsp; &nbsp; &nbsp; &nbsp; print(x)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; x = math.ceil(x)&nbsp; &nbsp; &nbsp; &nbsp; print(x)

繁星淼淼

你必须重新定义x,x = math.ceil(x)代码:import mathwhile True:&nbsp; &nbsp; x = float(input('Type something: '))&nbsp; &nbsp; if x-int(x) < 0.5:&nbsp; &nbsp; &nbsp; &nbsp; x = math.floor(x)&nbsp; &nbsp; &nbsp; &nbsp; print(x)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; x = math.ceil(x)&nbsp; &nbsp; &nbsp; &nbsp; print(x)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python