我的代码有问题。我在自学 c#,本章中的挑战之一是提示用户输入 10 个数字,将它们存储在一个数组中,而不是要求额外的 1 个数字。然后程序会说明附加数字是否与数组中的数字之一匹配。现在我下面的内容确实有效,但前提是我输入了一个小于 10 的比较数字,这是数组的大小。
我不知道如何解决它。我不知道如何进行比较。我首先尝试了一个 FOR 循环,哪种工作有效,但运行循环并显示与所有 10 个数字的比较,因此您将得到 9 行 No!和 1 行 Yes!。我休息一下;这停止了所有 10 的计数,但如果我输入数字 5 进行比较,那么我会得到 4 行 No!和 1 个是的!。下面是我可以让它可靠地工作的唯一方法,但前提是数字不超出数组的范围。
我可以理解为什么当数字大于 10 时会出现错误,我只是不知道用什么来比较它,但仍然允许用户输入任何有效的整数。任何帮助都会很棒!
int[] myNum = new int[10];
Console.WriteLine("Starting program ...");
Console.WriteLine("Please enter 10 numbers.");
for (int i = 0; i <= 9; ++i)
{
Console.Write("Number {0}: ", i + 1);
myNum[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers ");
foreach (int i in myNum)
{
Console.Write("{0} ", i);
}
Console.WriteLine("");
Console.Write("Please enter 1 additional number: ");
int myChoice = Int32.Parse(Console.ReadLine());
Console.WriteLine("Thank you. You entered the number {0}.", myChoice);
int compareArray = myNum[myChoice - 1];
if (compareArray == myChoice)
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
Console.WriteLine("End program ...");
Console.ReadLine();
最佳答案
如果包含 System.Linq 命名空间(或者如果将 myNum 的类型更改为实现 ICollection<T> 的类型,例如 List<T>
),则可以使用 myNum.Contains(myChoice)
来查看值 myChoice
是否与 myNum
中的值之一匹配。 array.Contains
返回一个 bool 值,如果在数组中找到指定的值,则返回 true
,否则返回 false
。
您可以更新您的代码以使用它,如下所示:
//int compareArray = myNum[myChoice - 1]; // This line is no longer needed
if (myNum.Contains(myChoice))
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
关于c# - 数组中的比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11025859/