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

if语句和2个数组的C#问题,c#,arrays,for-loop,if-statement,indexoutofboundsexception,C#,Arrays,For Loop,If Statement,Indexoutofboundsexception,代码一直运行到第二个for循环中的if语句。我尝试过改变很多东西——添加了第二个数组,这样它就不会与if语句冲突。调试了它,还更改了最后一个if的true语句,但它从未真正通过23行,并显示System.IndexOutOfRangeException:索引超出了数组的边界。 Console.WriteLine("Number of inputs: "); int numInput = int.Parse(Console.ReadLine());

代码一直运行到第二个for循环中的if语句。我尝试过改变很多东西——添加了第二个数组,这样它就不会与if语句冲突。调试了它,还更改了最后一个if的true语句,但它从未真正通过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");
Console.WriteLine(“输入数:”);
int numInput=int.Parse(Console.ReadLine());
int[]arrayOfNumbers=新的int[numInput];
int[]arrayOfNumbersClone=新int[numInput];
对于(int inc=0;incif(counter我认为这是因为您在for循环条件中使用了
inc2
,但从未真正为其赋值

将代码更改为

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

for(int inc2=0,dec=numInput;inc2
错误表明您试图获取数组中不存在的索引。因此只需添加检查条件:

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
        {                }

}
int计数器=0;
int lengthNumbers=arrayOfNumbers.Length;
int lengthNumbersClone=ArrayOfNumbersOne.Length;
for(int inc2=0,dec=numInput;maxInc
假设numInput=5

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

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

在您的if声明中,您请求arrayOfNumbersClone[dec]。 因为dec是5,所以您需要第5个索引上的元素。这是第6个项目,它不存在。因此您得到了“System.IndexOutOfRangeException”

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

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

(还请注意,未定义的“inc2”更改为“inc”)

您知道,在第二个循环中,您初始化“inc”,但测试并增加“inc2”,在“if”中,您使用从未修改过的“inc”?您必须初始化
dec=numInput-1