//dice throws to arrays
int throws = 1;
int[] oneDice = new int[throws];
int[,] twoDice = new int[throws,throws];
Console.WriteLine("Number of throws: ");
throws = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Trows one dice "+throws+" times: ");
for (int i = 0; i < throws; i++)
{
Random random = new Random();
oneDice[i] = random.Next(6);
Console.WriteLine(oneDice[i]);
}
它说我的阵列oneDice是出界的,但我不明白为什么......请帮我搞清楚。
答案 0 :(得分:-1)
你做错了就是用1声明你的数组,然后改变你的变量。更改变量不会更改您的数组声明,因此您必须承担索引超出范围的错误。
此外,您需要在random
之前添加loop
变量声明,以便每次都能获得不同的结果。
试试这个
Console.WriteLine("Number of throws: ");
int throws = Convert.ToInt32(Console.ReadLine());
int[] oneDice = new int[throws];
int[,] twoDice = new int[throws, throws];
Console.WriteLine("Trows one dice "+throws+" times: ");
Random random = new Random();
for (int i = 0; i<throws; i++)
{
// Random random = new Random();
oneDice[i] = random.Next(6);
Console.WriteLine(oneDice[i]);
}
答案 1 :(得分:-1)
Console.WriteLine("Number of throws: ");
int throws = Convert.ToInt32(Console.ReadLine());
int[] oneDice = new int[throws];
int[,] twoDice = new int[throws, throws];
Console.WriteLine("Throws one dice " + throws + " times: ");
Random random = new Random();
for (int i = 0; i < throws; i++)
{
oneDice[i] = random.Next(6);
Console.WriteLine(oneDice[i]);
}
错误是由您最初将数组的长度定义为1引起的。首先读取抛出的数量然后创建数组然后就没有问题。