我正在尝试模拟掷骰子。 Die_1 + Die_2五次。程序运行,但数学错误。我已尝试过多种方法,但无法正确判断数学。模具一次只能卷一个,所以一个和六个是可能的。这一定是过度疲惫的疏忽。任何想法都会很棒。代码和输出如下。感谢任何可以提供帮助的人。
# This program will simulate dice rolls 5 different
# times and add the total of each roll.
import random
import math
MIN = 1
MAX = 6
ROLLS = 5
def main():
for count in range(ROLLS):
die_1 = (random.randint(MIN, MAX))
die_2 = (random.randint(MIN, MAX))
combined_roll = point(die_1, die_2)
print('Here are the combined rolls for the dice!')
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))
print('The combined roll is:', combined_roll)
def point(die_1, die_2):
roll_1 = die_1 + die_2
combined_roll = roll_1
return combined_roll
main()
Here are the combined rolls for the dice!
4
3
The combined roll is: 4
Here are the combined rolls for the dice!
2
2
The combined roll is: 7
Here are the combined rolls for the dice!
5
4
The combined roll is: 5
Here are the combined rolls for the dice!
3
5
The combined roll is: 9
Here are the combined rolls for the dice!
3
1
The combined roll is: 11
答案 0 :(得分:2)
数学和一切都是正确的。这确实是累了的症状。
你在这两行中打印出全新的数字:
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))
与你的模具实际上相比,早些时候。
die_1 = (random.randint(MIN, MAX))
die_2 = (random.randint(MIN, MAX))
时间已经过去,因此您的随机数生成将处于不同的状态。
因此将打印件更改为:
print(die_1)
print(die_2)
答案 1 :(得分:1)
最好通过一个简单的函数和random.randint
:
>>> from random import randint
>>> def roll_dice(n=1):
... return [randint(1, 6) for _ in range(n)]
...
1-die roll:
>>> roll_dice()
[2]
>>> roll_dice()
[2]
>>> roll_dice()
[5]
2-die roll:
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[5, 5]
>>>
您可以通过以下方式轻松总计2个模具:
>>> sum(roll_dice(2))
6
>>> sum(roll_dice(2))
7
>>> sum(roll_dice(2))
8
答案 2 :(得分:0)
第二组如果print语句意味着打印die_1和die_2,则再次调用random。如果再次呼叫随机,则会获得新的随机数。