C#有关if语句和2个数组的问题

问题描述 投票:0回答:3

代码运行直到第二个for循环中的if语句。香港专业教育学院试图改变很多东西-添加了第二个数组,以便它与if语句不冲突。对其进行了调试,并更改了最后一个if的真实语句,但它从未真正通过23行,并且它显示System.IndexOutOfRangeException:索引超出数组的范围。

            Console.WriteLine("Number of inputs: ");
            int numInput = int.Parse(Console.ReadLine());
            int[] arrayOfNumbers = new int[numInput];
            int[] arrayOfNumbersClone = new int[numInput];
            for (int inc = 0; inc < arrayOfNumbers.Length; inc++)
            {
                Console.Write("Enter {0} element: ", inc + 1);
                arrayOfNumbers[inc] = Int32.Parse(Console.ReadLine());
                arrayOfNumbersClone[inc] = arrayOfNumbers[inc];
            }
            for (int inc = 0, dec = numInput; inc2 < dec; inc2++, dec--)
            {
                if (arrayOfNumbers[inc] == arrayOfNumbersClone[dec])
                {
                    counter++;
                }
                else
                {
                }

            }
            if(counter<=0)Console.WriteLine("The array is not symmetric");
            else Console.WriteLine("The array is symmetric");
c# arrays for-loop if-statement indexoutofboundsexception
3个回答
0
投票

我认为这是因为您在for循环条件中使用了inc2,但从未真正为其分配任何值

将您的代码更改为

for (int inc2 = 0, dec = numInput; inc2 < dec; inc2++, dec--)


0
投票

该错误表明您试图获取数组中不存在的索引。因此,只需添加检查条件:

int counter = 0;
int lengthNumbers = arrayOfNumbers.Length;
int lengthNumbersClone = arrayOfNumbersClone.Length;            
for (int inc2 = 0, dec = numInput; maxInc < dec; inc2++, dec--)
{
    if (inc2 < lengthNumbers
        && dec < lengthNumbersClone
        && arrayOfNumbers[inc2] == arrayOfNumbersClone[dec])
        {
           counter++;
        }
        else
        {                }

}

0
投票

假设numInput = 5。

然后,您将创建一个包含5个元素的数组。第5个元素的索引为4,因为索引从0开始计数。

在第二个循环中,您声明dec = numInput;因此,dec现在也是5。

在您的if语句中,您请求arrayOfNumbersClone [dec]。由于dec为5,因此您需要在第5个索引上提供元素。这是第六项,不存在。因此,您会收到“ System.IndexOutOfRangeException”

将第二个for循环更改为以下内容可以解决您的问题

for (int inc = 0, dec = numInput - 1; inc < dec; inc++, dec--)

(还要注意,未定义的'inc2'更改为'inc')]

© www.soinside.com 2019 - 2024. All rights reserved.