数组中每个参数的随机值

本文关键字:随机 参数 数组 | 更新日期: 2023-09-27 18:11:53

我的程序有问题。我想设置我的数组有多少个索引,然后为每个索引设置自己的随机值。而不是循环foreach为每个索引创建一个值。我尝试了for和数组的长度,但它不起作用。我做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Set the number of arguments in mineArray:");
            string argumentsNumber = Console.ReadLine();
            int argumentsNumberInt = Convert.ToInt32(argumentsNumber);
            int[] mineArray = new int[argumentsNumberInt];
            //set up values to each index of array
            for (int i = 0; i < mineArray.Length; i++)
            {
                Random rand = new Random();
                mineArray[i] = rand.Next(0, 100);
                Console.WriteLine(Convert.ToString(mineArray[i]));
            }
            //end of the program
            Console.ReadLine();
        }
    }
}

数组中每个参数的随机值

初始化随机循环:

Random rand = new Random();
for (int i = 0; i < mineArray.Length; i++)
{           
    mineArray[i] = rand.Next(0, 100);
    Console.WriteLine(mineArray[i]); // you don't need to convert to string
}

当你创建Random类的实例时,它使用当前系统的tick作为伪随机数生成的种子。如果你快速创建多个Random实例,它们会得到相同的种子,你将在数组中得到相同的数字。