为什么我的while循环不应该中断

问题描述 投票:0回答:1

我目前正在尝试运行一个模拟程序,其中棒球运动员有81%的机会击球,而目标是使棒球运动员连续获得56次击球。我已经设置好它,以便可以重复执行一百万次,但是如果玩家连续获得56次或更多击中它应该停止,并且会打印出玩家连续击中56次的尝试次数。但是,由于某些原因,当总命中数至少为56时,我的for循环不会停止(预测概率远低于1/1000000)。为什么我的循环无法正确断开?

import random
attempts = 0
totalhits = 0
def baseball():
    totalhits = 0
    hit = 1
    while hit == 1:
        odds = random.randint(1,100)
        if odds <= 81:
            hit = 1
            totalhits = totalhits + 1
        else:
            hit = 0
    return totalhits

for i in range(1,1000000):
    baseball()
    if totalhits >= 56:
        break
    attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

结果始终如一Attempt 999999 succeeded

python loops for-loop break
1个回答
0
投票

您没有从函数中返回“合计”。因此,每次比较“ totalhits”的值时,便会将其与初始值0进行比较。

您可以将for循环更改为:

© www.soinside.com 2019 - 2024. All rights reserved.