【发布时间】:2019-02-14 10:10:25
【问题描述】:
我正在制作一个彩票游戏,它要求用户输入 10 个数字,然后将其与我在数组中创建的随机数进行检查。我需要比较两者,但我不能使用 contains 方法。
我认为我需要使用 foreach 循环来比较数组,但实际上我不知道该怎么做。我一直在从我所知道的一点点拼凑起来,并想知道我是否走在正确的轨道上。
foreach 循环是比较两个数组的正确方法吗?
这是我目前的代码。
using System;
namespace lotto2
{
class Program
{
static void Main(string[] args)
{
//an array named "input" to hold the users' 10 guesses
int[] inputs = new int[10];
//an array named "lotNum" to hold 10 random numbers
int[] lotNums = new int[10];
//a for loop to loop over the inputs array. each loop will ask the user for a number
Console.WriteLine("Enter your 10 lottery numbers one at a time. The numbers must be between 1 and 25.");
for (int i = 0; i < inputs.Length; i++)
{
inputs[i] = Convert.ToInt32(Console.ReadLine());
}
//a random number generator
Random ranNum = new Random();
//loop to call the random generator 10 times and store 10 random numbers in the "lotNum" array
for (int i = 0; i < 10; i++)
{
lotNums[i] = ranNum.Next(1, 26); //chooses random numbers between 1 and 25
}
//writes out the randomly generated lotto numbers
Console.Write("\nThe lottery numbers are: ");
for (int i = 0; i < 10; i++)
{
Console.Write("{0} ", lotNums[i]);
}
//loop for checking users inputs against random generated numbers..
//foreach loop maybe?
foreach (var input in lotNums)
{
}
//print out if there are any matches, which numbers matched
//declared integer for the correct numbers the user guessed
int correct;
//end progam
Console.WriteLine("\n\nPress any key to end the program:");
Console.ReadKey();
}
}
}
【问题讨论】:
-
使用 LINQ 有什么问题?这是作业吗?
-
是的,我正在参加在线课程,这是一项作业。
-
这就是你不能使用 LINQ 的原因吗?
-
考虑先对它们进行排序。另一种选择是编写自己的 Contains 方法。
-
在这个作业中我不能使用 LINQ。