python - 下面的伪代码给出了一个算法来模拟掷骰子和计数面数
问题描述
以下伪代码提供了一种模拟掷骰子和计数面数的算法。
- 开始
- 初始化完成为假
- 虽然没有完成
- 如果 n 是设置为 true 的正整数,则提示用户输入正整数 n
- 否则输出有意义的错误信息提示用户再次尝试输入
- 初始化一个变量以存储 n 个整数(例如:掷骰子 30 次将存储 30 个不同的数字)
- 循环 n 次迭代,每掷一次骰子
- 生成 1 到 6 之间的整数
- 将生成的整数插入/附加到存储变量
- 初始化第二个存储变量以存储 1-6 之间的每个数字的计数(每个数字滚动了多少次)
- 循环 n 次或 6 次迭代,具体取决于您选择对此分配进行编码的方式
- 将第一个存储中的每个生成的整数(滚动数)计数到相应的计数存储
- 输出 6 个计数(例如:1 滚动 7 次,2 滚动 4 次,3 滚动 6 次,等等)
- 产量百分比分布(例如:1 是 23.33% 的卷,2 是 13.33% 的卷,3 是 20.00% 的卷等)
- 停止
我得到了第一部分,但没有得到其余的部分。谢谢!
#start() function to prompt user for a positive integer n with error checking and meaningful error messages.
done = False
while not done:
#try reading integer input from user
inputNumber = input('Enter a positive integer: ')
try:#if input is positive, output the data.
intInputNumber = int(inputNumber)
if intInputNumber > 0:
done = True
else:#if input is not positive, display error and call this function again
print("Please enter a positive integer. Try again!!")
except ValueError:#if input is not integer, handle error
print('Please enter an integer. Try again!!')
解决方案
你可以像这样使用python字典
#initialisation
mydictionary={'1':0,'2':0,'3':0,'4':0,'5':0,'6':0}
然后每次你得到一个有效的输入你做mydictionary[inputNumber]+=1
推荐阅读
- javascript - 白天每 15 分钟发送一次通知
- javascript - Firebase 函数在同一个 onCall 函数中读取和添加数据
- c# - 当通过单击按钮创建列表视图时,如何通过拖放在列表视图之间移动列表视图项?UWP C#
- wordpress - Wordpress 重定向到不存在的域
- node.js - 在我的电子应用中显示 Teams Web 应用
- numpy - numpy - 为什么 Z[(0,2)] 是视图但 Z[(0, 2), (0)] 是副本?
- c# - 如何在 VS 中用 C# 声明并用 C++ 实现?
- xamarin.forms - Xamarin.Forms AVPlayer 从方法中退出全屏
- html - 打开带有空号码的短信
- c++ - 如果不推荐使用 std::iterator,我们是否仍应使用需要 std::iterator 的类或函数?