c# - 陷入数组

标签 c# arrays random

所以我有一个包含 100 个 int 元素的数组,必须在 [-100,100] 范围内随机抽取,并且必须返回此范围 [-30,30] 内的奇数数量。我这样做:

int counter = 0;
int i = 0;
int[] numbers = new int[100];
for ( i = 0; i <= numbers.Length; i++)
{
    Random rnd = new Random();
    numbers[i] = rnd.Next(-100, 101);
    if (numbers[i] % 2 != 0)
    {
        if (numbers[i] >= -30 && numbers[i] <= 30)
        {
            counter++;
        }
    }
}
Console.WriteLine(counter);

而且我构建并没有收到任何错误。但是在运行时,我在命令提示符下收到此错误:System.IndexOutOfRangeException:索引超出了数组的范围。然后它引导我到这一行:

numbers[i]=rnd.Next(-100,101);

所以,就像,发生了什么事?我做错了什么?

最佳答案

替换<=<在for循环中。所以

for ( i = 0; i < numbers.Length; i++)

代替

for ( i = 0; i <= numbers.Length; i++)

集合在 .NET 中是基于零的。因此,您在索引 0 处找到第一项,在索引 99 处找到最后一项。


您还应该移动 Random在循环外初始化:

Random rnd = new Random();
for ( i = 0; i < numbers.Length; i++)
{
    // Random rnd = new Random();  <--- No, no!

因为 default constructor使用当前时间作为 Random 的种子.当您使用相同的种子时,您将始终生成相同的序列。由于循环执行得太快,因此使用了相同的种子。

引用:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers

关于c# - 陷入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33567257/

相关文章:

c# - 无需脚本即可在 ASP.NET 中使用 HiddenField 调用事件

c# - 将动态加载类型传递给 SomeFunction<T>

arrays - 尝试从 DocumentDirectory 路径获取图像时出错

java - Greenfoot/Java - 不兼容的类型 : boolean cannot be converted to int

php - 删除 level 1 array search by value on level 2

random - 数组长度范围内的 Ada 随机整数

algorithm - 给定一个真正的随机数生成器,每次调用输出 1 或 0,你如何使用它从任意范围中选择一个数字?

c# - ServiceStack执行存储过程需要很长时间

c# - 应用程序在非开发系统上崩溃

random - postman -如何生成特定范围内的随机数?