在Python中,整数除法向零舍入的好方法是什么? [英] In Python, what is a good way to round towards zero in integer division?

查看:162
本文介绍了在Python中,整数除法向零舍入的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1/2

给予

0

as这应该。但是,

-1/2

给予

-1

,但是无论它是正数还是负数,我都希望它向0舍入(即我希望-1/2为0)。最好的方法是什么?

, but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that?

推荐答案

进行浮点除法然后转换为int。不需要额外的模块。

Do floating point division then convert to an int. No extra modules needed.

Python 3:

>>> int(-1 / 2)
0
>>> int(-3 / 2)
-1
>>> int(1 / 2)
0
>>> int(3 / 2)
1

Python 2:

>>> int(float(-1) / 2)
0
>>> int(float(-3) / 2)
-1
>>> int(float(1) / 2)
0
>>> int(float(3) / 2)
1

这篇关于在Python中,整数除法向零舍入的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆