使用 Python来模拟掷两个骰子的情况 统计点数分布的情况

目录

需求:

代码实现:

程序说明:

运行结果:


需求:

使用 Python来模拟掷两个骰子的情况 统计点数分布的情况

代码实现:

复制代码
import random


def roll_dice():
    """模拟掷两个骰子的行为,并返回两个骰子的点数之和。"""
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    return dice1 + dice2


def simulate_dice_rolls(num_rolls=1000):
    """模拟掷两个骰子 num_rolls 次,并统计每种点数的分布情况。"""
    # 初始化统计字典
    rolls_distribution = {i: 0 for i in range(2, 13)}

    # 模拟掷骰子
    for _ in range(num_rolls):
        roll_result = roll_dice()
        rolls_distribution[roll_result] += 1

    return rolls_distribution


def print_results_with_percentage(distribution, total_rolls):
    """打印每种点数的出现次数和百分比。"""
    print("Point\tFrequency\tPercentage (%)")
    for point, frequency in distribution.items():
        percentage = (frequency / total_rolls) * 100
        print(f"{point}\t{frequency}\t\t{percentage:.2f}")


if __name__ == "__main__":
    # 模拟掷两个骰子 1000 次
    num_rolls = 1000
    results = simulate_dice_rolls(num_rolls)
    print_results_with_percentage(results, num_rolls)

程序说明:

  1. roll_dice() 函数

    • 使用 random.randint(1, 6) 来模拟掷一个六面骰子的行为。
    • 返回两个骰子的点数之和。
  2. simulate_dice_rolls() 函数

    • 初始化一个字典 rolls_distribution 用于存储每种点数的出现频率。
    • 使用 for 循环来模拟掷骰子的过程,每次调用 roll_dice() 并更新相应的统计值。
    • 最终返回统计结果。
  3. print_results() 函数

    • 打印每种点数的出现次数。

运行结果:

Point Frequency Percentage (%)

2 27 2.70

3 50 5.00

4 98 9.80

5 111 11.10

6 142 14.20

7 171 17.10

8 140 14.00

9 112 11.20

10 74 7.40

11 52 5.20

12 23 2.30

相关推荐
ayqy贾杰38 分钟前
GPT-5.5+Codex全自动搓出macOS游戏,创作链路首次真正连续
前端·面试·游戏开发
我喜欢山,也喜欢海44 分钟前
Java和go在并发上的表现为什么不一样
java·python·golang
Wenzar_2 小时前
**零信任架构下的微服务权限控制:用Go实现基于JWT的动态访问策略**在现代云原生环境中,
java·python·微服务·云原生·架构
不是起点的终点2 小时前
【实战】Python 一键生成数据库说明文档(对接阿里云百炼 AI,输出 Word 格式)
数据库·python·阿里云
英俊潇洒美少年3 小时前
Vue2/Vue3 vue-i18n完整改造流程(异步懒加载+后端接口请求)
前端·javascript·vue.js
2301_813599554 小时前
Go语言怎么做秒杀系统_Go语言秒杀系统实战教程【实用】
jvm·数据库·python
--fancy8 小时前
股票预测情感分析研究案例分析
python
shughui8 小时前
PyCharm 完整教程(旧版本卸载+旧/新版本下载安装+基础使用,2026最新版附安装包)
ide·python·pycharm
lUie INGA8 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
小糖学代码8 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc