我想为我的解决方案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;'。一旦你找到了好的结果,这将节省你做额外的工作。 –