使用 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

相关推荐
前端一课几秒前
【vue高频面试题】第 11 题:Vue 的 `nextTick` 是什么?为什么需要它?底层原理是什么?
前端·面试
前端一课1 分钟前
【vue高频面试题】第 10 题:`watch` VS `watchEffect` 的区别是什么?触发时机有什么不同?
前端·面试
小石头 100861 分钟前
【JavaEE】synchronized关键字
java·java-ee
悟空码字3 分钟前
Java实现接口幂等性:程序员的“后悔药”
java·后端
天天摸鱼的java工程师3 分钟前
🔍 MySQL 索引底层原理与 SQL 优化实战:从 B + 树到亿级查询优化
java·后端
h***34636 分钟前
SpringBoot3.3.0集成Knife4j4.5.0实战
android·前端·后端
Yanni4Night6 分钟前
数据可视化神器Heat.js:让你的数据热起来
前端·javascript
IMPYLH6 分钟前
Lua 的 select 函数
java·开发语言·笔记·后端·junit·游戏引擎·lua
Lazy_zheng6 分钟前
前端页面更新检测实战:一次关于「用户不刷新」的需求拉扯战
前端·vue.js·性能优化
小石头 100867 分钟前
【JavaEE】死锁和避免方法
java·java-ee