数组比较,学校任务不工作
本文关键字:工作 任务 学校 比较 数组 | 更新日期: 2023-09-27 18:02:25
第一个帖子,如果我做错了什么请告诉我:)
我有这样的代码:
static void Main(string[] args)
{
//declaring first array
Console.Write("Enter the size of the first the array: ");
int sizeOne = Int32.Parse(Console.ReadLine());
int[]firstArray = new int[sizeOne];
//fill it from console
for (int counter = 0; counter<=sizeOne - 1; counter++)
{
Console.Write("Please enter a value: ");
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(firstArray[counter]);
}
//declaring second array
Console.Write("Enter the size of the second array: ");
int sizeTwo = Int32.Parse(Console.ReadLine());
int[] secondArray = new int[sizeTwo];
//fill it from console
for (int counter = 0; counter <= sizeTwo - 1; counter++)
{
Console.Write("Please enter a value: ");
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(secondArray[counter]);
}
//compare size and values, as sidenote it could write not equal even
//when the user inputs two arrays with different lengths to save time :)
if (firstArray.Length == secondArray.Length)
{
for (int counter = 0; counter <= sizeOne; counter++)
{
if ((firstArray[counter]) != (secondArray[counter]))
{
Console.WriteLine("The two arrays aren't equal");
break;
}
else
{
Console.WriteLine("The two arrays are equal");
}
}
}
else
{
Console.WriteLine("The two arrays aren't equal");
}
}
应该比较数组的长度和元素。如果两个数组长度不同,但元素数相等,它总是写不相等。我错过了什么?
提前感谢您的帮助!
这是一个打字错误,或者复制粘贴错误,随便你怎么称呼它。在第二个循环中,当你应该填充secondArray
时,你错误地填充了firstArray
。这意味着secondArray
只有0。您可能很幸运(或不走运),因为firstArray
的大小总是等于或大于secondArray
。否则你就会得到一个异常,这可能会帮助你发现你的错误。
注意,一旦你修复了它,你也会得到一个越界异常,因为你的比较循环使用counter <= sizeOne
条件,这是错误的。它应该是counter < sizeOne
,否则您将越过数组的末尾。
稍微修改一下循环:您需要一个布尔标志,它指示是否存在不匹配。否则,如果只有第一个元素匹配,则输出"两个数组是相等的"。
if (firstArray.Length == secondArray.Length)
{
bool areEqual = true;
for (int counter = 0; counter < firstArray.Length; counter++)
{
if ((firstArray[counter]) != (secondArray[counter]))
{
areEqual = false;
//Console.WriteLine("The two arrays aren't equal");
break;
}
// This would get executed if the first elements are equal, but others are not
//else
//{
// Console.WriteLine("The two arrays are equal");
//}
}
if (areEqual)
Console.WriteLine("The two arrays are equal");
else
Console.WriteLine("The two arrays aren't equal");
}
然后当然有一个内置函数(在。net中)称为SequenceEqual
,它比较两个数组:
using System.Linq;
...
bool areEqual = firstArray.SequenceEqual(secondArray);
if (areEqual)
Console.WriteLine("The two arrays are equal");
else
Console.WriteLine("The two arrays aren't equal");
看到NetFiddle
还有一个错字:您填充了两次firststarray。
//fill it from console
for (int counter = 0; counter <= sizeTwo - 1; counter++)
{
Console.Write("Please enter a value: ");
// **Must be secondArray**
firstArray[counter] = Int32.Parse(Console.ReadLine());
//for test
// Console.WriteLine(secondArray[counter]);
}