尝试模拟 2 个骰子以了解相同结果的百分比
Trying to simulate 2 dice to know the percentage of same outcome
所以,我认为它们是代码中某处的逻辑错误。
无论我在输出终端中插入任何数字,输出都保持 运行 0%
#dice - count doubles in user - defined number of rounds.. repeated
import random
#simulate rolling a six sided die and return its value.
def rollOneDie():
#generate random numbers from 1 to 6
thisFace = random.randrange(1,7)
return thisFace
while True:
nDoubles = 0
maxRounds = input(
"how many rounds do you want to roll?(or ENTER to quit):")
if maxRounds == '':
break
try:
maxRounds = int(maxRounds)
except:
print("please an integer number")
continue
for roundNumbers in range(0, maxRounds):
die1 = rollOneDie()
die2 = rollOneDie()
if die1 == die2:
nDoubles = nDoubles + 1
percent = (nDoubles * 100.0) / maxRounds
print('out of ', maxRounds, 'you rolled',
nDoubles, 'doubles or ', percent, '%')
print('ok byeee')
它打印 0% 的原因是检查骰子是否相同的 if 语句在“掷”骰子的 for 循环之外,所以只有当骰子相同时 nDoubles 才增加 1上次你“滚动”它们的时间。
正确的方法是:
for roundNumbers in range(0, maxRounds):
die1 = rollOneDie()
die2 = rollOneDie()
if die1 == die2:
nDoubles = nDoubles + 1
另外,你可以这样写:
nDoubles += 1
而不是
nDoubles = nDoubles + 1
所以,我认为它们是代码中某处的逻辑错误。 无论我在输出终端中插入任何数字,输出都保持 运行 0%
#dice - count doubles in user - defined number of rounds.. repeated
import random
#simulate rolling a six sided die and return its value.
def rollOneDie():
#generate random numbers from 1 to 6
thisFace = random.randrange(1,7)
return thisFace
while True:
nDoubles = 0
maxRounds = input(
"how many rounds do you want to roll?(or ENTER to quit):")
if maxRounds == '':
break
try:
maxRounds = int(maxRounds)
except:
print("please an integer number")
continue
for roundNumbers in range(0, maxRounds):
die1 = rollOneDie()
die2 = rollOneDie()
if die1 == die2:
nDoubles = nDoubles + 1
percent = (nDoubles * 100.0) / maxRounds
print('out of ', maxRounds, 'you rolled',
nDoubles, 'doubles or ', percent, '%')
print('ok byeee')
它打印 0% 的原因是检查骰子是否相同的 if 语句在“掷”骰子的 for 循环之外,所以只有当骰子相同时 nDoubles 才增加 1上次你“滚动”它们的时间。
正确的方法是:
for roundNumbers in range(0, maxRounds):
die1 = rollOneDie()
die2 = rollOneDie()
if die1 == die2:
nDoubles = nDoubles + 1
另外,你可以这样写:
nDoubles += 1
而不是
nDoubles = nDoubles + 1