基本的Python算术-除法 [英] Basic python arithmetic - division
问题描述
我有两个变量:count(这是我过滤后的对象的数量)和常数per_page.我想将count除以per_page并获得整数值,但是无论我尝试什么,我都得到0或0.0:
I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 :
>>> count = friends.count()
>>> print count
1
>>> per_page = 2
>>> print per_page
2
>>> pages = math.ceil(count/per_pages)
>>> print pages
0.0
>>> pages = float(count/per_pages)
>>> print pages
0.0
我在做什么错,为什么math.ceil给出浮点数而不是int?
What am I doing wrong, and why math.ceil gives float number instead of int ?
推荐答案
当两个操作数均为整数时,Python进行整数除法,这意味着1 / 2
基本上是"2变成1的次数",当然是0时代.要执行所需的操作,请按照您的期望将一个操作数转换为浮点数:1 / float(2) == 0.5
.而且,math.ceil(1 / float(2))
当然会产生您期望的1
.
Python does integer division when both operands are integers, meaning that 1 / 2
is basically "how many times does 2 go into 1", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5
, as you're expecting. And, of course, math.ceil(1 / float(2))
will yield 1
, as you expect.
(我认为这种划分行为在Python 3中会发生变化.)
(I think this division behavior changes in Python 3.)
这篇关于基本的Python算术-除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!