Python骰子程序,随机整数不变

2024-03-28 11:51:19 发布

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

我正在尝试写一个小代码,它可以掷骰子,然后记录掷6的次数。可以想象,我使用的是random.randint(1,6)。但是,对于每个连续的抛出,只需重复随机整数。我猜这可能是我的while循环的结构,我是一个完全的新手,所以任何帮助都将不胜感激

#import random module
import random

#introduce the program
print("a program to count the number of 6's thrown in a simulation of a dice being thrown 6000 times")

#declare the variables
max = int(6) #need to declare max number for the dice
min = int(1) #need to declare min number for the dice
throw = random.randint(1,6) #each throw of the dice generates a number
countThrow = 0 #count the number of throws
maxThrow = int(6) #max throw
sixRolled = 0 #count the number of 6's thrown

#while loop

while countThrow != maxThrow:
    countThrow = countThrow + 1
    print(throw)
    print("Number of rolls ", countThrow)

    if throw == 6:
        sixRolled = sixRolled + 1
        print("You have thrown a", throw)

    else:
        print("you have rolled a", throw, "roll again.")
        

print("You have rolled ", sixRolled, "6's in 6 throws")

非常感谢


Tags: ofthetonumbercountrandomdicemax
2条回答

您缺少while循环中的随机项。 请参阅下面的代码,我在循环中插入了随机数

while countThrow != maxThrow:
    countThrow = countThrow + 1
    throw = random.randint(1, 6) # you should insert the random in the loop
    print(throw)
    print("Number of rolls ", countThrow)

    if throw == 6:
        sixRolled = sixRolled + 1
        print("You have thrown a", throw)

    else:
        print("you have rolled a", throw, "roll again.")

因为您只调用throw = random.randint(1,6) 一次

您需要将其添加到循环中以继续生成随机数

#import random module
import random

#introduce the program
print("a program to count the number of 6's thrown in a simulation of a dice being thrown 6000 times")

#declare the variables
max = int(6) #need to declare max number for the dice
min = int(1) #need to declare min number for the dice

countThrow = 0 #count the number of throws
maxThrow = int(6) #max throw
sixRolled = 0 #count the number of 6's thrown

#while loop

while countThrow != maxThrow:
    throw = random.randint(1,6) #each throw of the dice generates a number
    countThrow = countThrow + 1
    print(throw)
    print("Number of rolls ", countThrow)

    if throw == 6:
        sixRolled = sixRolled + 1
        print("You have thrown a", throw)

    else:
        print("you have rolled a", throw, "roll again.")
        

print("You have rolled ", sixRolled, "6's in 6 throws")

相关问题 更多 >