如何检查我的数组是否分别包含猜测的数字?

时间:2015-06-09 02:24:07

标签: c# arrays

如果我的数组包含各自顺序的随机数(1,2,3,4,5,6,7),我想创建另一个猜测数组(1,4,2,4,5,6, 7),我想分别看看我有多少是正确的。

这是我的代码:

Console.WriteLine("Can you guess the numbers that have appeared on the screen respectively?");
        for (int i = 1; i < num.Length; i++)
        {
            Console.Write(i + ". ");
            string temp = Console.ReadLine();
            userGuess[i] = Convert.ToInt32(temp);

        }

        for (int i = 1; i < num.Length; i++)
        {
            if (num[i] == userGuess[i])//Here's my problem. I am unable to 
                                       //test whether my guess resides in the num array.
            {
                count++;
            }
        }

        Console.WriteLine("You got " + count + " guesses right.");
如果我选择1,4,2,4,5,6,7判断我的num数组分别包含1,2,3,4,5,6,7,那么计数应该以5正确结束。

谢谢!

2 个答案:

答案 0 :(得分:0)

由于两个数组长度相等,您可以使用LINQ的Zip()方法:

var result = num.Zip(userGuess, (n, u) => n == u ? 1 : 0).Sum();

这会比较两个列表中的每个对应元素,为匹配返回1或为不匹配返回0,然后将值相加。结果实际上是匹配的数量。

答案 1 :(得分:0)

就像@failedprogramming所说,你在数组userGuess和num之间的错配匹配索引。 我知道你想用no。“1”启动用户输入但是,它会让你的userguess数组移动到错误的索引。

1     2    3    4    5    6    7
blank 1    4    2    4    5    6  

所以,你没有正确答案。

也许你可以使用它:

Console.WriteLine("Can you guess the numbers that have appeared on the screen respectively?");
            for (int i = 1; i < num.Length+1; i++)
            {
                Console.Write(i + ". ");
                string temp = Console.ReadLine();
                userGuess[i-1] = Convert.ToInt32(temp);

            }

            for (int i = 0; i < num.Length; i++)
            {
                if (num[i] == userGuess[i])//Here's my problem. I am unable to 
                //test whether my guess resides in the num array.
                {
                    count++;
                }
            }

            Console.WriteLine("You got " + count + " guesses right.");