不确定将随机数写入数组c#

时间:2015-08-29 13:11:23

标签: c# arrays

我是c#的新手,并不理解100%如何将值存储到数组中。我的代码需要随机生成最大数量为28毫米的降雨量值。它有25%的几率在任何一天发生。我目前收到一个错误'无法将类型'int'转换为'int []'。我打算将数字插入每个月的每一天。任何帮助都将不胜感激。

class Program {        
    enum Months {January = 1, February, March, April, May, June, July, 
                 August, September, October, November, December}        
    static int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    const int MONTHS_IN_YEAR = 12;

    static void Main(string[] args) 
    {
       int[][] rainfall = new int[MONTHS_IN_YEAR] [];
       Welcome();
       ExitProgram();
    }//end Main
    static void Welcome() {
        Console.WriteLine("\n\n\t Welcome to Yearly Rainfall Report \n\n");
    }//end Welcome
    static void ExitProgram() {
        Console.Write("\n\nPress any key to exit.");
        Console.ReadKey();
    }//end ExitProgram
    static void GetRainfall(int[] daysInMonth, string[] Months, int[][] rainfall)
    {
        Random chanceOfRain = new Random(3);
        Random rainfallAmount = new Random(28);
        int j;
        for (int i = 0; i < daysInMonth.Length; i++)
        {
            j = chanceOfRain.Next(3);
            if (j == 0)
            {
                rainfall[i] = rainfallAmount.Next(28);
            }
        }
    }//end ChanceOfRain

1 个答案:

答案 0 :(得分:2)

您将rainfall[i]定义为二维数组,因此int[]int的数组。您正尝试为此数组分配 rainfall[i] = rainfallAmount.Next(28);

 rainfall[i][j] = rainfallAmount.Next(28);

应该是这样的:

rainfall[i][j] = new int[5]; // if you want 5 elements

for eaxmple。

在使用之前不要忘记初始化数组的每一行:

static void GetRainfall(int[] daysInMonth, string[] Months, int[][] rainfall)
{
    Random chanceOfRain = new Random(3);
    Random rainfallAmount = new Random(28);
    int j;
    for(int m = 0; m < MONTHS_IN_YEAR; m++)
    { 
       rainfall[m] = new int[daysInMonth.Length];
       for (int i = 0; i < daysInMonth.Length; i++)
       {
           j = chanceOfRain.Next(100);
           if (j < 25)//25% chance
           {
               rainfall[m][i] = rainfallAmount.Next(28);
           }
       }
    }
}//end ChanceOfRain     

我认为你需要这个:

cartdesignsizes

代码迭代数月并初始化该月的数组,该月份的天数。然后它迭代几天并生成值。