-2

我试图让用户输入 10 个数字并将它们存储到数组中。然后提示用户输入任何数字以检查该数字是否已存储在数组中。当我输入任何数字时,屏幕将消失,我无法验证该数字是否已存在。请看我的代码。提前致谢。

static void Main(string[] args)
    {
        int[] numCheck = new int[10];
        int[] userInput = new int[1];

        Console.WriteLine("Please enter 10 numbers: ");

        for (int i = 0; i < 10; i++)
        {
            Console.Write("Number {0}: ", i + 1);
            numCheck[i] = int.Parse(Console.ReadLine());
        }

        Console.WriteLine("Please enter any number to check if the number already exist");

        for (int j = 0; j <= 10; j++)
        {
            if (userInput == numCheck)
            {
                Console.Write("The number {0} is in the index", numCheck);
                userInput[j] = int.Parse(Console.ReadLine());
            }

            else 
            {
                Console.Write("The number {} is not in the index", numCheck);
            }
        }
4

3 回答 3

4

您只从用户那里获取 1 项,因此无需声明数组

int userInput;

//read userInput

if (numCheck.Any(i => i == userInput))
{
    Console.Write("The number {0} is in the index", userInput);
}
else
{
    Console.Write("The number {} is not in the index", userInput);
}
于 2012-12-31T23:58:26.823 回答
1

这不应该:

if (userInput == numCheck)

是:

if (userInput[0] == numCheck[j])
于 2012-12-31T23:56:21.863 回答
1

建议的替代方案:

static void Main(string[] args)
{
    int[] numCheck = new int[10];
    Console.WriteLine("Please enter 10 numbers: ");

    for (int i = 0; i < 10; i++)
    {
        Console.Write("Number {0}: ", i + 1);
        numCheck[i] = int.Parse(Console.ReadLine());
    }

    Console.WriteLine("Please enter any number to check if the number already exist");
    int userInput = int.Parse(Console.ReadLine());

    for (int i = 0; i < 10; i++)
    {
        if (userInput == numCheck[i])
        {
            Console.Write("FOUND NUMBER");

            break;
        }
    }
 }
于 2013-01-01T00:01:21.467 回答