这是练习:
编写一个程序,它从控制台读取两个数组,并检查它们是否相等(当两个数组长度相等且所有元素具有相同的索引时,它们相等)。
这是我的代码:
//Declaration, Initialization.
Console.Write("First array size: ");
int sizeOfFirstArray = int.Parse(Console.ReadLine());
int[] firstArray = new int[sizeOfFirstArray];
Console.Write("Second array size: ");
int sizeOfSecondArray = int.Parse(Console.ReadLine());
int[] secondArray= new int[sizeOfSecondArray];
// Checking if Array's are equal.
bool isEqual = true;
for (int a = 0; a < firstArray.Length; a++)
{
Console.WriteLine("Enter first array's values of element: {0}", a);
firstArray[a] = int.Parse(Console.ReadLine());
}
for (int b = 0; b < secondArray.Length; b++)
{
Console.WriteLine("Enter second array's values of element: {0}", b);
secondArray[b] = int.Parse(Console.ReadLine());
}
if (firstArray[firstArray.Length] != secondArray[secondArray.Length]) // This gives me an error Index was out of bounds
{
isEqual = false;
}$
我想用for循环解决这个练习。
问题: 第38行给出了一个错误:索引超出了数组边界。
答案 0 :(得分:0)
错误的直接原因在于
if (firstArray[firstArray.Length]...
由于数组从零开始,因此它们具有[0..Length - 1]
个索引项;你的意思是
// if lengths (not items!) are different then arrays are not equal
if (firstArray.Length != secondArray.Length) {
isEqual = false;
}
按照书中所写的那样做:
...
// Two arrays are equal if they are of equal length...
bool isEqual = a.Length == b.Length;
// ..and all of their elements which have the same index, are equal
if (isEqual) // We don't need to scan arrays if they are not equal by their lengths
for (int i = 0; i < a.Length; ++i)
if (a[i] != b[i]) {
isEqual = false; // 1st counter example has been found
// we don't need to loop any more if a counter example has been found
break;
}
请注意,在真实世界中我们放
bool isEqual = a.SequenceEqual(b);