将一个int值与一个数组进行比较,然后显示该值是否匹配或不匹配。

9
我是一个新手程序员,对C#很感兴趣。我正在学习数组并且必须将我的变量(checkNum)与我的数组(myNums [10])进行比较。我在这里阅读了帖子和其他几个网站,看到了如何比较,但卡在了如何正确显示比较结果上,就像我在下面的if / else语句中的尝试一样:(我会继续研究,但会欣赏指导方向的提示。我不一定要答案,因为我想学习):)
这是我的代码:
int[] myNums = new int[10];
int checkNum;
Console.WriteLine("Enter 10 numbers:");

for (int i = 0; i < 10; i++)
{
    Console.Write("Number {0}: ", i + 1);
    myNums[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("You entered:");
foreach (int x in myNums)
{
    Console.Write("{0} ", x);
}
Console.ReadLine();

Console.WriteLine("Enter another number:");
checkNum = int.Parse(Console.ReadLine());
bool exists = myNums.Contains(checkNum);

if (checkNum == myNums[10])
{
    Console.WriteLine("Your number {0} is in the Array.", checkNum);
}
else
{
    Console.WriteLine(
        "Your number {0} does not match any number in the Array.",
        checkNum);
}
Console.ReadLine();

1
除了有关数组边界和不使用已存在变量的所有答案之外,我还要补充一点,通常最好使用int.TryParse(string, out int)来避免错误输入。 - Nickolodeon
1
向他人寻求帮助而不是直接索要答案,这是一个好习惯。 - Mark Peters
3个回答

6
bool exists = myNums.Contains( checkNum );
if( checkNum == myNums[10] )
{
    Console.WriteLine( "Your number {0} is in the Array.", checkNum );
}
else
{
    Console.WriteLine( "Your number {0} does not match any number in the Array.", checkNum );
}

应该是

bool exists = myNums.Contains( checkNum );
// or simply if(myNums.Contains(checkNum)) as you don't use the variable again
if( exists )
{
    Console.WriteLine( "Your number {0} is in the Array.", checkNum );
}
else
{
    Console.WriteLine( "Your number {0} does not match any number in the Array.", checkNum );
}

您正确地执行了检查,但您没有使用结果(exists),而只是(尝试)将新数字与数组中的最后一个元素进行比较。当然,在这一点上,您的程序会崩溃,因为您已经超出了数组的边界。
数组是从0开始编号的,即nums[10]包含索引0-9。

包含(Contains)会让我的代码变得更简单。 :) ++ - John
谢谢。现在我明白了,是使用了其他变量来进行“if”语句的比较,而不是使用布尔变量“exists”。感谢您。 - Darwin

0
为什么你在最后一个 if 语句中检查 checkNum == myNums[10]? 应该使用 exists 变量。

0
你需要遍历数组来查看其中是否包含该值:
bool exists = false;
for (int i=0; i<myNums.Length; i++)
{
    if (checkNum == myNums[i])
    {
        exists = true;
        break;
    }
}

if (exists)
{
    Console.WriteLine("Your number {0} is in the Array.", checkNum);
}
else
{
    Console.WriteLine(
        "Your number {0} does not match any number in the Array.",
        checkNum);
}

Contains() 更加简单易用。 - Ed S.
包含操作更简单,但通过迭代可以获得更好的结果,因为您可以看到哪个索引相等,哪个不相等。 - Gustavo Maciel
那么您可以使用 IndexOf 并检查是否为 -1,在代码中仍然不需要循环。OP 无需了解索引。 - Ed S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接