首页 > 解决方案 > 下面的伪代码给出了一个算法来模拟掷骰子和计数面数

问题描述

以下伪代码提供了一种模拟掷骰子和计数面数的算法。

  1. 开始
  2. 初始化完成为假
  3. 虽然没有完成
  1. 初始化一个变量以存储 n 个整数(例如:掷骰子 30 次将存储 30 个不同的数字)
  2. 循环 n 次迭代,每掷一次骰子
  1. 初始化第二个存储变量以存储 1-6 之间的每个数字的计数(每个数字滚动了多少次)
  2. 循环 n 次或 6 次迭代,具体取决于您选择对此分配进行编码的方式
  1. 输出 6 个计数(例如:1 滚动 7 次,2 滚动 4 次,3 滚动 6 次,等等)
  2. 产量百分比分布(例如:1 是 23.33% 的卷,2 是 13.33% 的卷,3 是 20.00% 的卷等)
  3. 停止

我得到了第一部分,但没有得到其余的部分。谢谢!

#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

解决方案


你可以像这样使用python字典

#initialisation
mydictionary={'1':0,'2':0,'3':0,'4':0,'5':0,'6':0}

然后每次你得到一个有效的输入你做mydictionary[inputNumber]+=1


推荐阅读