您好我正在写一个代码,在12个月内每天随机抽查,看看是否下雨以及下雨多少。然而,当我想将它存储在2D数组中时,它恰好有一个错误,我很困惑,我该如何解决它? 我已经在程序开始时声明了这些
static int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const int MONTHS_IN_YEAR = 12;
这是有问题的方法
static void MakeItRain(int[][] rainfall)
{
Random Rainfall = new Random(10);
Random RainOrNot = new Random(10);
for (int j = 0; j < MONTHS_IN_YEAR; j++)
{
for (int i = 0; i < (daysInMonth[j]); i++)
{
if (RainOrNot.Next(1, 5) == 1)
{
rainfall[i][j] = Rainfall.Next(1, 28);
}
}
}
}
答案 0 :(得分:2)
当您首先按"GUI.h"
初始化此锯齿状数组时,必须使用正确的索引填充它
a <- "attgctagctagtcatgctagctacgtacgcatcgtacgatgcatatgctttttaattt"
你注意到了吗?第二个数组未初始化。这意味着你不能做例如
MONTHS_IN_YEAR
你必须先初始化第二个数组
int[][] rainfall = new int[MONTHS_IN_YEAR][];
现在你的代码应该是这样的
rainfall[0][0] = something;
答案 1 :(得分:0)
我能够成功运行您的代码,但在“降雨”时遇到了IndexOutOfRangeException。传递给MakeItRain方法的数组太小,无法在方法内部进行迭代。
成功运行:
public class Program
{
static int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const int MONTHS_IN_YEAR = 12;
public void Main(string[] args)
{
int[,] rain = new int[31, MONTHS_IN_YEAR];
MakeItRain(rain);
}
static void MakeItRain(int[,] rainfall)
{
Random Rainfall = new Random(10);
Random RainOrNot = new Random(10);
for (int j = 0; j < MONTHS_IN_YEAR; j++)
{
for (int i = 0; i < (daysInMonth[j]); i++)
{
if (RainOrNot.Next(1, 5) == 1)
{
rainfall[i,j] = Rainfall.Next(1, 28);
}
}
}
}
}