我正在为自己编写一个程序,我需要在特定数字之间做一个随机的.在两个数字之间的字段中不是随机的,在几个特定数字之间随机出现.我想用15个不同的数字来做这件事,但是如果有人能给我一个例子,只有少数会很精彩!
将您的数字存储在一个数组中,然后选择一个随机索引:
var nums = new int[] { 1, 5, 7, 14, 17 };
var rand = new Random();
var randIndex = rand.Next(nums.Length);
var theRandomSelection = nums[randIndex];
// do something with theRandomSelection
Run Code Online (Sandbox Code Playgroud)
只需用数字填充数组,然后随机选择索引.伪代码:
int numbers = new List<int>(){1, 2, 4, 7, 8};
Random r = new Random();
int index = r.Next(numbers.Count);
int randomNumber = numbers[index];
Run Code Online (Sandbox Code Playgroud)