C#数组和Random.NextDouble()的奇怪行为

用户3051029

我在main()方法中有以下代码

    const int Length = 20;
    const int NumberOfExperiments = 100;
    static void Main(string[] args)
    {
        Random gen = new Random();
        double[][] arr = new double[NumberOfExperiments][];
        for (int j = 0; j < NumberOfExperiments; ++j)
        {
            arr[j] = new double[Length + 4];
            for (int i = 0; i < Length; ++i)
            {
                arr[j][i] = gen.NextDouble();
            }
            arr[j][Length] = bubbleSort(arr[j]);
            arr[j][Length + 1] = insertSort(arr[j]);
            arr[j][Length + 2] = arr[j][Length] - arr[j][Length + 1];
            arr[j][Length + 3] = arr[j][Length + 2] * arr[j][Length + 2];
            foreach(double memb in arr[j]){
                Console.WriteLine("{0}", memb);
            }
            Console.ReadKey();
        }
        WriteExcel(arr, "sorting");

        Console.ReadKey();
    }

在第一个ReadKey()之后,我有以下输出:

0
0
0
0 0.046667384
0.178001223
0.197902503
0.206131403
0.24464349
0.306212793
0.307806501
0.354127458
0.385836004
0.389128544
0.431109518
0.489858235
0.530548627
0.558604611
0.647516463
0.762527595
0.874646365
152 -151.1253536
22838.87251

我不知道为什么数组的前几个元素都用0填充。第一次迭代总是以i=0(或j=0开始,所以没关系。功能bubbleSort()insertSort()正常工作和回报掉期的数量。我已经使用C#了几年了,但是我真的不明白为什么这段代码不起作用。

布拉德利网

创建“行”时,请执行以下操作:

arr[j] = new double[Length + 4];

但是然后像这样循环:

for (int i = 0; i < Length; ++i)

因此,最后4个元素保留默认值(0)。当您进行排序时,这些元素会从头开始。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章