如何用python编写汇总脚本

2024-05-16 15:01:05 发布

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

如果一个拼车停车场有33人33辆车,如果每辆车能容纳4人,需要多少辆车?停车场还有多少辆车?你知道吗

我知道答案是9,但我该怎么写剧本呢。我为此挣扎了好几个小时。你知道吗

cars = 33
people = 33
people_per_car = 4
cars_needed = people / people_per_car
cars_left_at_lot = cars - cars_needed
print cars_needed
print cars_left_at_lot

我错了8分!你知道吗

8
25

Tags: 答案peoplecarcarsleftatlotprint
3条回答

这是因为在python2中,当两个操作数都是整数时,会执行整数除法,默认情况下会向下舍入:

 >>> 33/4
 8 
 >>> 33/4.0 # Note that one of operands is float
 8.25
 >>> math.ceil(33/4.0)
 9.0

在python3中,除法在默认情况下是以浮点方式执行的(但我猜这是不相关的)。你知道吗

如果还有剩余车辆,您需要添加一辆额外的车辆:

cars_needed = people / people_per_car
if people % people_per_car:
    cars_needed += 1

好的,您需要使用python 3.3或float命令来禁用自动舍入:

from math import ceil
cars = 33
people = 33
people_per_car = 4
cars_needed = int(ceil(1.* people / people_per_car))
cars_left_at_lot = cars - cars_needed
print cars_needed
print cars_left_at_lot

在Python2.7中,如果数字的类型是int,那么数字会自动四舍五入。*它将数字转换为浮点数。天花板将向上舍入而不是向下舍入。你知道吗

相关问题 更多 >