gpt4 book ai didi

python - 用python模拟滚动2个六面骰子的总和

转载 作者:行者123 更新时间:2023-11-30 23:30:34 32 4
gpt4 key购买 nike

编写 2 个六面骰子滚动的模拟。你的程序应该有一个函数 Roll() 来返回掷骰子的总和。您可以假设六个面中的每一个都有相同的可能性被掷出(即骰子是“公平的”)。运行模拟 1000 次并报告每次总和发生的频率。

到目前为止我已经有了这个,但我的程序似乎不会将总和加起来。我可能完全错了。请提供任何帮助。我认为我的主要问题在于我的打印声明。我需要输出来打印 2 的总和、3 的总和、4 的总和等显示多少次,直到 12。

def Roll():
for i in range(1000):
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
dice1= float(0)
dice2= float(0)

dice1 = random.randint(1,6)
if dice1 == 1:
one = one + 1
count= 1
return count
elif dice1 == 2:
two = two + 1
count= 1
return count
elif dice1 == 3:
three = three + 1
count= 1
return count
elif dice1 == 4:
four = four + 1
count= 1
return count
elif dice1 == 5:
five = five + 1
count= 1
return count
else:
six = six + 1
count= 1
return count

dice2 = random.randint(1,6)
if dice2 == 1:
one = one + 1
elif dice2 == 2:
two = two + 1
elif dice2 == 3:
three = three + 1
elif dice2 == 4:
four = four + 1
elif dice2 == 5:
five = five + 1
else:
six = six + 1

total = one + two + three + four + five + six

print("2", dice1 + dice2)
print("3", dice1 + dice2)
print("4", dice1 + dice2)
print("5", dice1 + dice2)
print("6", dice1 + dice2)
print("7", dice1 + dice2)
print("8", dice1 + dice2)
print("9", dice1 + dice2)
print("10", dice1 + dice2)
print("11", dice1 + dice2)
print("12", dice1 + dice2)

最佳答案

我已经用相同的作业回答了你的 friend :

import random
from collections import defaultdict

def main():
dice = int(input("Enter the number of dice: "))
sides = int(input("Enter the number of sides: "))
rolls = int(input("Enter the number of rolls to simulate: "))
result = roll(dice, sides, rolls)
maxH = 0
for i in range(dice, dice * sides + 1):
if result[i] / rolls > maxH: maxH = result[i] / rolls
for i in range(dice, dice * sides + 1):
print('{:2d}{:10d}{:8.2%} {}'.format(i, result[i], result[i] / rolls, '#' * int(result[i] / rolls / maxH * 40)))


def roll(dice, sides, rolls):
d = defaultdict(int)
for _ in range(rolls):
d[sum(random.randint(1, sides) for _ in range(dice))] += 1
return d

main()

你可以取出对你有用的部分。这还应该涵盖后续问题,例如:“如何整齐地打印它”和“如何绘制直方图”。

<小时/>

示例:

Enter the number of dice: 2
Enter the number of sides: 6
Enter the number of rolls to simulate: 1000
2 28 2.80% ######
3 59 5.90% #############
4 84 8.40% ###################
5 96 9.60% ######################
6 155 15.50% ####################################
7 170 17.00% ########################################
8 147 14.70% ##################################
9 102 10.20% #######################
10 80 8.00% ##################
11 50 5.00% ###########
12 29 2.90% ######

关于python - 用python模拟滚动2个六面骰子的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501379/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com