我尝试使用此代码计算超过速度限制的汽车百分比,除非第二个循环中存在错误,我不确定如何使用循环来增加数量汽车超过限速。我的最终目标是打印出超过速度限制的汽车百分比。我是编程的新手,所以任何提示或帮助都会受到赞赏,谢谢: - )
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
if speed > speedLimit
carsAboveLimit =+ 1
i = i +1
percent = int(carsAboveLimit)/len(carSpeeds)
print("The percentage of cars over the speed limit is", percent)
答案 0 :(得分:1)
if speed > speedLimit
carsAboveLimit
已经是int
;你不需要再这样做。
=+
不是运营商; +=
是
对于百分比,您需要乘以100.即
pct = 100. * carsAboveLimit / len(carSpeeds)
我建议写一下
def get_int(prompt):
while True: # repeat until we get an integer
try:
return int(input(prompt))
except ValueError:
# that wasn't an integer! Try again.
pass
def get_speeds():
while True:
speed = get_int("Enter a car speed (or 0 to exit): ")
if speed == 0:
break
yield speed
def main():
# get list of car speeds
car_speeds = list(get_speeds())
# get number of speeders
limit = get_int("What's the speed limit? ")
num_speeders = sum(1 for speed in car_speeds if speed > limit)
# show % of speeders
pct = 100. * num_speeders / len(car_speeds)
print("{:0.1f} % of them are speeding!".format(pct))
main()
答案 1 :(得分:1)
你正在做一个欧几里德分部。 carsAboveLimit
的类型为int
,len(carSpeeds)
也是一样。
如果你想获得百分比,只需乘以一个浮点数(通常为1.
),如下所示:
percent = 1. * int(carsAboveLimit)/len(carSpeeds)
答案 2 :(得分:1)
主要问题是
if
声明if
语句只执行一次,你没有把它放在一个循环中您可以将if
语句更改为:
for car_speed in carSpeeds:
if car_speed > speedLimit:
carsAboveLimit += 1
这样做是通过列表中的每个项目。每次car_speed
的值成为列表中的下一个项目。
而是指定float
并乘以100:
percent = 100 * float(carsAboveLimit)/len(carSpeeds)
你应该先尝试一下,先看看我的意思,然后你可以把它改成:
print "The percentage of cars over the speed limit is %0.2f%%" % percent
请注意,Python中常见的变量约定是使用下划线而不是camelCase。也就是说,尝试使用:speed_limit
代替speedLimit
。
您不需要i
变量。我的猜测是你试图有一个计数器来跟踪循环可能吗?无论哪种方式都没有必要。
答案 3 :(得分:0)
你面临的问题是a)铸造浮动能够得到一个小数部分,因为int / int - > int和int / float - >浮动。
>>> 1/2
0
>>> 1/float(2)
0.5
和b)正确格式化结果以显示为百分比值(假设您需要2位小数):
>>> '%0.2f%%' % (1/float(2))
'0.50%'
您的代码将完整如下(包括其他用户提到的一些小细节 - 在if块,增量运算符等处冒号)。请注意代码中缺少的for
循环,但提到了:
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
for speed in carSpeeds:
if speed > speedLimit:
carsAboveLimit += 1
i += i
percent = int(carsAboveLimit)/float(len(carSpeeds))
print("The percentage of cars over the speed limit is %0.2f%%" % percent)
输出:
Enter the number of cars: 3
Enter the car speed: 1
Enter the car speed: 2
Enter the car speed: 3
Enter the speed limit: 2
The percentage of cars over the speed limit is 0.33%