如何让随机数生成器方法循环并生成新的随机数?在Main之前我需要一个单独的类来处理随机数生成吗?如果是这样,我如何将这些变量的范围变为Main?控制台应用程序应该重复整数数学问题来练习一个条件正确或不正确答案的循环。另外,我忽略了什么语法循环回到随机生成的整数的新实例? TIA。
public class Multiplication
{
public static void Main(string[] args)
{
Random randomNumbers = new Random(); // random number generator
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
int value = 0;
while (true)
{
if (value != -1)
{
Console.Write("Please enter the answer to {0} x {1} = ?", num01, num02);
int product = num01 * num02;
Console.WriteLine();
int answer = Convert.ToInt32(Console.ReadLine());
while (product != answer)
{
Console.WriteLine("Incorrect, enter another guess: ");
answer = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Correct. Your answer was {0} \n {1} x {2} = {3} Very good!",
answer, num01, num02, product);
//keep console open
Console.WriteLine();
Console.WriteLine("Press - 1 to exit");
value = Convert.ToInt32(Console.ReadLine());
}
else
{
break;
}
}
}
}
答案 0 :(得分:5)
将随机数生成放在循环中,而不是之前。
int value = 0;
while (true)
{
if (value != -1)
{
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
...
答案 1 :(得分:1)
随机数生成器语句必须在循环中。我需要调整console.writeline以包含“类型1继续”。所以最终的代码是:
public class Multiplication
{
public static void Main(string[] args)
{
int value = 1;
while (true)
{
if (value == -1)
{
break;
}
else
{
Random randomNumbers = new Random(); // random number generator
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
Console.Write("Please enter the answer to {0} x {1} = ?", num01, num02);
int product = num01 * num02;
Console.WriteLine();
int answer = Convert.ToInt32(Console.ReadLine());
while (product != answer)
{
Console.WriteLine("Incorrect, enter another guess: ");
answer = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Correct. Your answer was {0} \n {1} x {2} = {3} Very good!",
answer, num01, num02, product);
//keep console open
Console.WriteLine();
Console.WriteLine("Press - 1 to exit or 1 to continue");
value = Convert.ToInt32(Console.ReadLine());
}
}
}
}