【问题标题】:Unsure with writing random numbers into arrays c#不确定将随机数写入数组c#
【发布时间】:2015-08-29 13:11:23
【问题描述】:

我是 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

【问题讨论】:

  • 你从哪里得到错误?
  • 最后一行雨量[i] =雨量.Next(28);
  • rainfall[i][j] = rainfallAmount.Next(28);
  • 感谢您的帮助!

标签: c# arrays


【解决方案1】:

您将rainfall 定义为二维数组,因此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

我认为你需要这个:

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     

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 2014-12-21
    • 1970-01-01
    • 2018-09-26
    • 2019-03-23
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    相关资源
    最近更新 更多