我刚刚学习了C#的基础知识,现在我尝试创建一个控制台MCQ,以随机顺序打印问题,并在每次用户再次使用MCQ时打印不同的选项。但有时相同的选项有时会被打印在一起......这是我的代码......
attr_accessor :password
答案 0 :(得分:1)
我建议您使用此方法以随机顺序生成整数列表(我已经在代码的摘录中实现了它)
//create an enumerable containing the numbers 0,1,2,3 and randomize it
Random r = new Random();
int[] options = Enumerable.Range(0, 4).OrderBy(o => r.Next()).ToArray();
//prints options
foreach (int option in options)
{
if (mcq.optionsBool[x, option] == true) //replaced 'y' with 'option'
{
int z = gen.Next(4);
Console.WriteLine("[" + optionCount + "]" + mcq.options[x, z]);
mcq.optionsBool[x, z] = true;
}
else //there are only two possible outcomes(TRUE/FALSE) so use Else instead of ElseIf
{
Console.WriteLine("[" + optionCount + "]" + mcq.options[x, option]);
mcq.optionsBool[x, option] = true;
}
Wait(1); //These two lines were present on
optionCount++; //both if and else, so I placed them outside
}
您的代码有很多可以改进/简化的内容,我建议您在CodeReview中显示代码,它们会告诉您如何改进代码
编辑:我忍不住改进你的代码,所以这就是我的方法: static void printQn()
{
Questions mcq = new Questions();
Random r = new Random();
//Randomize question indexes and grab first
int[] questions = Enumerable.Range(0, mcq.questions.Length).OrderBy(q => r.Next()).ToArray();
int question = questions.First();
//Print first question
Console.WriteLine(mcq.questions[question]);
Wait(2);
//Randomize option indexes (GetLength(1) will return the size of the 'y' dimension of the options array, so 4)
int[] options = Enumerable.Range(0, mcq.options.GetLength(1)).OrderBy(o => r.Next()).ToArray();
//prints options
int optionCount = 1;
foreach (int option in options)
{
Console.WriteLine("[{0}] {1}", optionCount, mcq.options[question, option]);
Wait(1);
optionCount++;
}
}
您仍然必须实现管理用户编写的响应的部分,并将其与optionsBool数组进行对比,以匹配它是否正确答案,但我会留给您;)