python - 有没有办法知道在 python 中某些东西是向上还是向下取整?
问题描述
我基本上想知道我的方程的结果(这是一个像这样的简单方程x / y
)是向上还是向下舍入。原因是我在舍入线之后有两个简单的语句,如下所示:
if h % 2 != 0: h = h + 1
if h % 4 != 0: h = h + 2
并且根据舍入的方向,我会选择+
or-
运算符,所以如果结果向上取整,h % 2 != 0
那么它就是h = h + 1
,如果它被向下取整,那么h = h - 1
.
会round()
提供那种信息吗?
另外,我的数学正确吗?(我希望结果可以被 4 整除)
解决方案
试试这个直接四舍五入:
import math
h = 53.75
rounded = math.round(h / 4) * 4
if (rounded > h):
print("Rounded up by " + str(rounded - h))
else:
print("Rounded down by " + str(h - rounded))
推荐阅读
- powershell - 将 Powershell 中命令的字符串输出解析为对象数组
- javascript - Typescript将两种数据类型数组合二为一
- javascript - 卡片 onclick 组件未呈现
- javascript - 克隆表单字段并增加 id
- javascript - 当我在 React.js 中更改活动页面时,如何将我的数据保存在页面中?
- swift - 如何在 Amplify on AWS 中编辑数据模型以获得一对零或一的基数
- python-3.x - 这是对已部署的 Flask 应用程序进行更改的有效方法吗?
- r - 如何有选择地将R列拆分为单独的列
- extjs - 在分页中的 ext.js 中的网格中搜索元素
- javascript - 如何在 Lit 的 css 中使用字符串类名