[英]C# Issues with if-statement and 2 arrays
代码一直运行到第二个 for 循环中的 if 语句。 我尝试过改变很多东西——添加了第二个数组,这样它就不会与 if 语句冲突。 对其进行了调试并更改了最后一个 if 的真实语句,但它从未真正通过第 23 行,它显示System.IndexOutOfRangeException: Index was outside the bounds of the array。
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");
我认为这是因为您在 for 循环条件中使用了inc2
但从未真正为其分配任何值
将您的代码更改为
for (int inc2 = 0, dec = numInput; inc2 < dec; inc2++, dec--)
该错误表示您试图获取数组中不存在的索引。 所以只需添加检查条件:
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
{ }
}
假设 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--)
(另请注意,未定义的 'inc2' 更改为 'inc')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.