【发布时间】:2016-11-16 10:38:48
【问题描述】:
我刚刚学习了 C# 的基础知识,现在我正在尝试创建一个控制台 MCQ,它以随机顺序打印问题,并在每次用户再次使用 MCQ 时打印不同的选项。但有时相同的选项有时会打印在一起......这是我的代码......
class Program
{
static void Wait(int sec)
{
Task.Delay(TimeSpan.FromSeconds(sec)).Wait();
}
static void printQn()
{
Questions mcq = new Questions();
Random gen = new Random();
//prints question 1
int optionCount = 1;
int x = gen.Next(5);
Console.WriteLine(mcq.questions[x]);
Wait(2);
mcq.questionsBool[x] = true;
//prints options
while (optionCount < 5)
{
int y = gen.Next(4);
if (mcq.optionsBool[x, y] == true)
{
int z = gen.Next(4);
Console.WriteLine("[" + optionCount + "]" + mcq.options[x, z]);
mcq.optionsBool[x, z] = true;
Wait(1);
optionCount++;
}
else if (mcq.optionsBool[x,y] == false)
{
Console.WriteLine("[" + optionCount + "]" + mcq.options[x, y]);
mcq.optionsBool[x, y] = true;
Wait(1);
optionCount++;
}
}
}
static void Main(string[] args)
{
printQn();
Console.ReadKey();
}
class Questions
{
public string[] questions =
{"Who was the first Queen of England?",
"What is the biggest island on Earth?",
"How many Grand Slam singles titles has Roger Federer won? ",
"When was the Euro introduced as legal currency on the world market? ",
"What year was the first Harry Potter movie released?"
};
public bool[] questionsBool = {false,false,false,false,false};
public string[,] options =
{ { "Queen Elizabeth I","Queen Mary I","Queen Anne" ,"Queen Matilda", },
{ "Hawaii" ,"Singapore" ,"Greenland" ,"Luzon ", },
{ "19" ,"17" ,"14" ,"15" , },
{ "Jan 1 1999" ,"Feb 1 1999" ,"Feb 13 1999","Feb 7 1998" , },
{ "2002" ,"1999" ,"2001" ,"2003" }};
public bool[,] optionsBool = { {false, false, false, false },
{false, false, false, false },
{false, false, false, false },
{false, false, false, false },
{false, false, false, false } };
}
}
}
【问题讨论】:
-
你正在生成一个随机数,下一次迭代,可以再次生成相同的数字。你尝试过什么来规避它?有两个选项:记住您已经使用过哪些选项,如果再次出现使用过的选项,则生成另一个数字,这可能会证明很麻烦和/或显示,或者改为将选项列表随机化一次。
-
@CodeCaster 你是对的......我想到了,但是如果当我生成另一个数字时,又会生成相同的数字怎么办?我该如何解决这个问题?如果没有,我如何将选项列表随机化一次?
标签: c# console-application options