[英]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.