【问题标题】:Random.randint produces same answer each run - or is my code faulty?Random.randint 每次运行都会产生相同的答案 - 还是我的代码有问题?
【发布时间】:2015-09-08 21:30:19
【问题描述】:

我想重复抛硬币 500 次,然后重复该实验 30 次,并打印每次运行的反面总数 (1)。只是运行正面/反面很容易,但是当我乱来尝试重复这个(第一个 while 循环)时,我每次运行都会得到完全相同数量的反面,这是不可能的。

虽然我是一个完整的新手,但我无法弄清楚我在这里做错了什么......谢谢!

import random
i=0
count_1=0 
rand_count=0
while rand_count<31:
    while i < 501:
        y=random.randint(0,1)
        if y ==1:
            count_1=count_1+1
        i=i+1
    rand_count=rand_count+1
    print(count_1)

【问题讨论】:

  • 一旦i &lt; 501 为假一次,你怎么期望它再次为真?

标签: python random while-loop


【解决方案1】:

您只需在两个循环之外重置count_1i 一次。它们需要在外循环内重置。这将有助于使用变量名和循环结构,使代码更易于阅读:

import random

for trials in range(30):

    count_1 = 0
    for samples in range(500):
        if 1 == random.randint(0, 1):
            count_1 += 1

    print(count_1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 2016-02-21
    • 2012-05-02
    • 2012-03-16
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多