函数题:掷骰子 - 实验15 拥抱对象 - 《Python编程基础及应用实验教程》- 高教社
下述代码可以生成值为1~6的“均匀分布”的随机整数。
import random
print(random.randint(1,6))
在公平的不出千的赌局中,骰子投掷的结果是随机且均匀分布的。请设计一个Dice类,使其可以被下述代码所使用,并产生期望的输出结果(random.seed(0)设置了随机数种子,以便得到一致的输出结果)。
### 类接口定义:
python
class Dice:
pass
### 裁判测试程序样例:
python
#在这里设计Dice类
import random
random.seed(0) #设置随机数种子,以便让执行结果固定
d = Dice()
print("-----Roll dice for 100 times-----")
for x in range(100):
r = d.rollDice()
if x < 10:
print(r,end=",")
print("...")
print("-----Statistics of rolling the dice-----")
for i in range(1,d.iSides+1):
sideCount = d.sideCount(i)
rollCount = d.rollCount()
print(f"Side {i}: {sideCount}/{rollCount} = "\
f"{sideCount*100/rollCount:.1f}%")
### 输入样例:
无输入
in
### 输出样例:
out
-----Roll dice for 100 times-----
4,4,1,3,5,4,4,3,4,3,...
-----Statistics of rolling the dice-----
Side 1: 16/100 = 16.0%
Side 2: 15/100 = 15.0%
Side 3: 19/100 = 19.0%
Side 4: 15/100 = 15.0%
Side 5: 24/100 = 24.0%
Side 6: 11/100 = 11.0%
<br>
建议的Dice类图:

<br>
如果读者期望观察“随机”的结果,请删除random.seed(0)。
答案:若无答案欢迎评论
import random
print(random.randint(1,6))
在公平的不出千的赌局中,骰子投掷的结果是随机且均匀分布的。请设计一个Dice类,使其可以被下述代码所使用,并产生期望的输出结果(random.seed(0)设置了随机数种子,以便得到一致的输出结果)。
### 类接口定义:
python
class Dice:
pass
### 裁判测试程序样例:
python
#在这里设计Dice类
import random
random.seed(0) #设置随机数种子,以便让执行结果固定
d = Dice()
print("-----Roll dice for 100 times-----")
for x in range(100):
r = d.rollDice()
if x < 10:
print(r,end=",")
print("...")
print("-----Statistics of rolling the dice-----")
for i in range(1,d.iSides+1):
sideCount = d.sideCount(i)
rollCount = d.rollCount()
print(f"Side {i}: {sideCount}/{rollCount} = "\
f"{sideCount*100/rollCount:.1f}%")
### 输入样例:
无输入
in
### 输出样例:
out
-----Roll dice for 100 times-----
4,4,1,3,5,4,4,3,4,3,...
-----Statistics of rolling the dice-----
Side 1: 16/100 = 16.0%
Side 2: 15/100 = 15.0%
Side 3: 19/100 = 19.0%
Side 4: 15/100 = 15.0%
Side 5: 24/100 = 24.0%
Side 6: 11/100 = 11.0%
<br>
建议的Dice类图:

<br>
如果读者期望观察“随机”的结果,请删除random.seed(0)。
答案:若无答案欢迎评论