簡體   English   中英

C#,在數組中查找重復項,索引超出了數組的范圍

[英]C#, Finding duplicates in arrays, Index was outside the bounds of the array

無法弄清為什么winningNumbers[i] += count; 出現在數組范圍之外。

static int[] CheckWinningNumbers(int[][]lottoNumbers, int[]drawNumbers)
                {
                    int[] winningNumbers = new int[8];
                    for (int i = 0; i < lottoNumbers.Length; i++)
                    {
                        int k = 0;
                        int count = 0;
                        for (int j = 0; j < lottoNumbers[i].Length; j++)
                        {
                            if (lottoNumbers[i][j] == drawNumbers[k])
                            {
                                count +=1;
                            }
                            k += 1;
                        winningNumbers[i] += count;
                        }
                    }       
                return winningNumbers;

只需更換

int[] winningNumbers = new int[8];

int[] winningNumbers = new int[lottoNumbers.Length];

只要您迭代lottoNumbers.Length ,變量i就不會超出其邊界。

編輯

我用以下數據運行它,它可以工作

 int[][] lottoNumbers = { new[] { 1, 2 },                                       
                          new[]{ 3, 4 }, 
                          new[]{ 5, 6 }, 
                          new[]{ 7, 8 } };
 int[] drawNumbers = {1, 4, 5, 8};

我不知道您要測試什么數據,但是您正在使用交錯的多維數組交錯數組 不能保證您所有的子數組都具有相同的長度,這可能會有問題。 如果所有數組的長度都相同且性能並不重要,建議您使用多維數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM