在python程序中正确添加数字时出错

2024-06-01 08:04:50 发布

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

我试着模拟骰子被掷。死亡1+死亡2五次。程序运行,但数学是错误的。我试过很多种方法,但都不能把数学弄好。模具一次只能滚动一个,所以1和6是可能的。这一定是一个过度疲劳的疏忽。任何想法都太棒了。代码和输出如下。谢谢任何能帮忙的人。你知道吗

# 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

Tags: theforhereisrandommindiceare
3条回答

数学和一切都是正确的。这确实是疲劳的症状。你知道吗

在这两行中打印出全新的数字:

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)

这最好通过一个简单的函数和random.randint来实现:

>>> from random import randint
>>> def roll_dice(n=1):
...     return [randint(1, 6) for _ in range(n)]
...

1模辊:

>>> roll_dice()
[2]
>>> roll_dice()
[2]
>>> roll_dice()
[5]

2模辊:

>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[5, 5]
>>>

您可以通过以下方式轻松地对两模辊进行求和:

>>> sum(roll_dice(2))
6
>>> sum(roll_dice(2))
7
>>> sum(roll_dice(2))
8

第二组如果print语句表示打印die_1和die_2,则nit再次调用random。如果你再叫random,你会得到新的随机数。你知道吗

相关问题 更多 >