如何计算末班车上有多少人

2024-10-05 15:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算一下末班车上有多少人。 我没找到工作。在

我知道我计算的第一个也错了。它一定是“//”,但它不起作用,然后用了“round()”,它对我有用。在

所以如果我选择:

人数259,座位数40,那么答案必须是

  • 需要的公共汽车数为7,最后一辆公共汽车的座位数为19

但我得到:

  • 需要6辆公共汽车,最后一辆公共汽车有19个座位

我的代码:

peop = int(input("Number of people: "))
bus  = int(input("Number of bus seats: "))

div  = round(peop / bus)

if (div <= 0) :
    print("Number of bus needed: " + str(1))
else:
    print("Number of bus needed: " + str(div))
cal = round(peop % bus)
if (cal == 0):
    print("In last bus number of people: " + str(bus))
else:
    print("In last bus number of people: " + str(cal))

Tags: ofdivnumberinputifpeoplecalint
2条回答

round()提供最接近浮点值的整数。259/40是6.475,最接近的整数是6。 你需要的是下一个比你的浮点数高的整数。您可以使用math.ceil(x)进行此操作:

import math
div = math.ceil(peop / bus)

有两件事需要注意!在

1)你要顶住而不是转!在

import math
math.ceil(peop/bus)

2)可以是(应该是下面的python2)

^{pr2}$

得到正确的余数

那是Python2

>>> peop/bus
6
>>> peop/float(bus)
6.475
>>> round(peop/float(bus))
6.0
>>> math.ceil(peop/float(bus))
7.0

在Python3中

>>> peop/bus
6.475
>>> import math
>>> from math import ceil
>>> ceil(peop/bus)
7

相关问题 更多 >