我想爲我的解決方案For循環轉換爲Foreach循環。而For循環產生我想要的輸出(見下文)。的foreach生成以下錯誤:訪問數組項目:「For」循環工作和「Foreach」給出System.IndexOutOfRangeException
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
public static bool sumOfTwo(int[] a, int[] b, int v)
{
bool result = false;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < b.Length; j++)
{
if (a[i] + b[j] == v)
{
result = true;
}
}
}
return result;
}
和我的foreach實現:那可能會錯呢?
public static bool sumOfTwo(int[] a, int[] b, int v)
{
bool result = false;
foreach (int i in a)
{
foreach (int j in b)
{
if (a[i] + b[j] == v)
result = true;
}
}
return result;
}
您正在使用數組「a」和數組「b」中的值來索引數組,這就是問題所在。你想要的是 - > bool result = false; (i + j == v) result = true;如果(i + j == v) 結果= true;如果(i + j == v) 結果=真;如果(i + j == v) 結果=真; } } 返回結果; –
另請參見:只在'if()'條件中'返回true;'。一旦你找到了好的結果,這將節省你做額外的工作。 –