【发布时间】:2021-02-27 06:46:19
【问题描述】:
我正在尝试执行一项任务,并且尝试通过提取我可以从数组中获得的可能性来记录两次掷骰子的结果。基本上,如果我掷出 2、4、5、5 和 2,我会记录我得到两个 2、一个 4 和两个 5。但是,我试图找出记录它的最佳方法,而不必诉诸于列出每个变量 2-12。有人可以帮助我学习如何从我提供的代码中创建快捷方式吗?代码如下:
using System;
namespace Assignment
{
class Program
{
static void Main(string[] args)
{
//Initialize variable(s).
int diceRollNum = 0;
//Create the array.
int[] DiceResultArray = new int[11];
//Create the random number.
Random diceRoll = new Random();
//Write out Headers.
Console.WriteLine($"Roll\tCount");
//
for (diceRollNum = 0; diceRollNum < 36000; diceRollNum++)
{
//Roll the dice.
int firstDice = diceRoll.Next(1, 6);
int secondDice = diceRoll.Next(1, 6);
//Add the dice sums.
diceRollNum = firstDice + secondDice;
//Record results.
DiceResultArray[diceRollNum] =
}
//
for (int i = 0; i < DiceResultArray.Length; i++)
{
Console.WriteLine($"{i+2}\t{DiceResultArray[i]}");
}
}
}
}
我们正在寻找“记录结果”评论下发生的具体情况。如果有人能帮我解释一下,那就太好了!
【问题讨论】:
-
你为什么不想这样做
var DiceResultArray = new int[12]; DiceResultArray[diceRollNum]++;? -
这绝对可以工作,尽管执行下面的建议可能更简单。我只需要了解如何为数组创建索引。