骰子程序C#.net使用数组
本文关键字:数组 net 子程序 | 更新日期: 2023-09-27 18:24:11
我的程序需要一些帮助,我构建了一个简单的骰子程序来显示100次掷骰子的两个骰子之和的频率。程序将读取该文件。
现在,我需要声明一个数组,该数组表示两个骰子投掷的可能结果。对于文件中的每个条目,递增与该结果对应的数组元素。最后,显示该模拟的频率计数。我不知道如何在程序中使用数组,需要帮助将其实现到程序中。
namespace Dice_Program
{
public partial class RollDice : Form
{
private int Dice1;
private int Dice2;
private int SUM;
const int Roll_MAX = 100;
private void btn_roll_Click(object sender, EventArgs e)
{
Random rand = new Random();
for (int lineNum = 1; lineNum <= Roll_MAX; lineNum++)
{
Dice1 = rand.Next(6) + 1;
Dice2 = rand.Next(6) + 1;
SUM = Dice1 + Dice2;
lstboxtotal.Items.Add(" On roll. " + lineNum + " You rolled a, " + Dice1 + " and a " + Dice2 + " for a sum of " + SUM);
}
}
private void btnwrite_Click(object sender, EventArgs e)
{ // Create a StreamWriter object
StreamWriter rollLog;
rollLog = File.CreateText ("Roll Results.txt"); // Creating the file
for (int count = 0; count <lstboxtotal.Items.Count; count++)
{
rollLog.WriteLine(Convert.ToString(lstboxtotal.Items[count]));
}
rollLog.Close(); // close file after creation
MessageBox.Show ("Your results have been successfully Saved to file.");
} // only first line is written 100 times
private void btnread_Click(object sender, EventArgs e)
{
using (StreamReader rollLog = new StreamReader("Roll Results.txt"))
{
while (rollLog.Peek() >= 0)
{
lstboxtotal.Items.Add(rollLog.ReadLine());
}
}
}
}
}
我理解你的英语有点困难。但我认为你想要这样的东西。
(*请注意,这是一种伪代码,不会立即编译,但我不会做你的功课)
int[] Rolls = { 0, 0, 0, 0, 0, 0 }; // 1 dice = 6 possible rolls 1- 6
void RollDice() {
int randomRoll = GetRandomDiceRoll(); //assume this returns 1-6 for the roll
//We use randomRoll-1 becuase the array is zero-indexed E.g. 0-5
Rolls[randomRoll-1]++;
//This increments the value and if the roll was 3 for instance your array will look like
// { 0, 0, 1, 0, 0, 0 }
}