不确定如何将随机数写入数组
本文关键字:数组 随机数 不确定 | 更新日期: 2023-09-27 18:10:31
我是c#新手,不完全了解如何将值存储到数组中。我的代码需要随机生成降雨量值,最大数量为28mm。它在任何一天都有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
您将rainfall
定义为二维数组,因此rainfall[i]
是int[]
的数组。您正在尝试使用int
rainfall[i] = rainfallAmount.Next(28);
应该是这样的:
rainfall[i][j] = rainfallAmount.Next(28);
eaxmple 。
不要忘记在使用数组之前初始化数组的每一行:
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
代码遍历月份并初始化当月的数组,该数组的天数为该月的天数。然后它逐日迭代并生成值。