python - 如何根据用户输入的浮点数编写“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)
解决方案
你可以这样检查:
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)
推荐阅读
- websocket - 为什么我的 Socket.IO 服务器没有响应我的 Firecamp 和 C# 客户端?
- python - 如何在 Apache 服务器上托管 Dash 应用程序?
- c# - 如何使用 Powershell 在 Windows 10 上处理 LogonHours 属性?
- virtual-machine - 如何实现像 virtualbox 这样的虚拟化应用程序?
- lisp - 过滤掉除数字以外的任何值
- r - Sparklyr 无法从 Dockerfile 中的 apache 下载 Spark
- reactjs - Formik handleReset 正在通过验证
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'C:\\Users\\SUN\\Desktop\\oops in python.txt'
- python - 有效地为 matplotlib 中 2 x 值之间的所有点着色
- java - 如何从 AbstractGatewayFilterFactory 中的 Flux 获取数据