python - 将奇数舍入为偶数的最佳方法是什么?

标签 python math integer rounding legacy

当我偶然发现以下内容时,我正在重写一些遗留代码:

rounded_val = (len(src_string)/2) * 2

这利用了 integer division behavior , 将字符串的长度值四舍五入到 它之前的第一个偶数值。但是整数除法在 Python 3 上即将发生变化,我需要更改这一行。

执行此操作的最佳方法是什么?

最佳答案

如果您不喜欢依赖 Python 2 / 整数操作数的行为,请改用 // 底除法:

rounded_val = (len(src_string) // 2) * 2

关于python - 将奇数舍入为偶数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154885/

相关文章:

delphi - 查找十进制编码十六进制值的正确公式

java - 如何在不使用 java.math.BigInteger 的情况下在 Java 中处理非常大的数字

python - 为什么 printf 使用 python 中的 ctypes 不打印有符号的数字

python - 属性错误 : 'module' object has no attribute

python - Http响应错误: This request is not authorized to perform this operation using this permission in Python Azure Function

python - 有没有办法将我的 python 脚本(我在 Ubuntu docker 镜像中编写的)转换为 Windows 的可执行文件?

java - 旋转矩形后得到一个点

algorithm - 我如何证明某个指数幂的所有常数都属于某个函数的 little-o

php - 在 PHP 中从一位、两位或三位整数生成 4 位整数

Python/selenium 网络抓取