您好,我的跑马程序运行出错。本质上,我只想在最后一部分输入名称,它应该为每个名称起一个作用。用户输入XXX后,命名将停止,比赛开始。任何帮助都可以。我将向您展示该程序的运行方式。
我的错误只发生在E部分
import random
print ("Random number from 10-21 is : " )
print (random.randrange(10,21))
##get the average
def average(times):
return sum(times) / len(times)
times = []
counter = 0
while counter < (1001):
counter += 1
times.append(random.randrange(10,21))
print (average(times))
## for one horse in the race
distance = 0
seconds = 1
while distance <= 10560:
distance += (random.randrange(4,41))
seconds += 1
print(distance)
##one horse running 1000 races
seconds = 0
distance = 0
times = []
counter = 0
while counter < (1001):
counter += 1
while distance <= 10560:
num = (random.randrange(4,41))
distance += num
seconds += 1
times.append(seconds)
print("Part C, Average of horses time", average(times))
##function that adds the random distance the horse
def horse(x):
b = random.randrange(4,41)
x = x + b
return x
##Part D
number_of_ = int(input("How many horses are in the race: "))
distance = []
for i in range(number_of_):
distance.append(0)
finishline = True
print(distance)
while finishline:
for p in range(len(distance)):
distance[p] = horse(distance[p])
if max(distance) <= 10560:
finishline = True
else:
finishline = False
print(distance)
print("The winner is" , max(distance))
#part E
name_of_horses = []
distance_of_horses = []
STOP = "XXX"
names = input("Enter a name for each horse: ")
while names != STOP:
name_of_horses.append(names)
names = input("Enter a name for each horse: ")
for i in range(len(names)):
distance_of_horses.append(0)
finishline = True
print(name_of_horses)
while finishline:
for p in range(len(distance_of_horses)):
distance_of_horses[p] = horse(distance_of_horses[p])
if max(distance_of_horses) <= 10560:
finishline = True
else:
finishline = False
print(distance_of_horses)
print("The winner is" , max(distance_of_horses))
下面提供的是程序当前返回的内容。我知道我是菜鸟,但任何帮助都可以。谢谢。
==================
Random number from 10-21 is :
11
15.036963036963037
10567
Part C, Average of horses time 245.0
How many horses are in the race: 5
[0, 0, 0, 0, 0]
[10588, 10532, 10444, 10461, 10362]
The winner is 10588
Enter a name for each horse: dom
Enter a name for each horse: dom
Enter a name for each horse: dom
Enter a name for each horse: dom
Enter a name for each horse: dom
Enter a name for each horse: dom
Enter a name for each horse: XXX
['dom', 'dom', 'dom', 'dom', 'dom', 'dom']
[10477, 10574, 10251]
The winner is 10574
答案 0 :(得分:2)
问题出在第78行
for i in range(len(names)):
distance_of_horses.append(0)
由于程序读取的名称被视为字符串(并且字符串是一个字符数组),因此会将您的字符串视为字符数组,在这种情况下,“ XXX”为3个字符,因此您的distance_of_horses当然会有3个值
经典的错误输入错误
注意:我不认为这应该在答案部分,但我还不能发表评论