c#While循环中的随机类

时间:2016-06-09 20:04:17

标签: c#

 while (true)
 {         
     Console.Write("What is: " + num03 + " x " + num04 + " = ");
     int answer = Convert.ToInt32(Console.ReadLine());
     if (answer == num03 * num04)
     {
         Console.WriteLine("Correct");
         num03 = randNum.Next(10) + 1;
         num04 = randNum.Next(10) + 1;
         continue;
     }
     else
     {
         Console.WriteLine("Incorrect");
         continue;
     }
 }// End of while loop

我是C#的新手(2周)随机化简单的数学总和。 是否有更简单或更紧凑的方法为每个变量编写randNum.Next()

1 个答案:

答案 0 :(得分:1)

没有比这更简短的方法,除非你使用一些lambda或其他方法这样做:

var rnd = new Random(); // add a seed if required
Func<int> randNum = () => rnd.Next(1, 11); // I think your intent was to get a number between 1 and 11 right? You can always change that

while(true)
{
     Console.Write("What is: " + num03 + " x " + num04 + " = ");
     int answer = Convert.ToInt32(Console.ReadLine());
     if (answer == num03 * num04)
     {
         Console.WriteLine("Correct");
         num03 = randNum();
         num04 = randNum();
     }
     else
     {
         Console.WriteLine("Incorrect");
     }
}

注意我删除了continue,因为你不需要它们,因为你覆盖了if的两种情况,所以无论执行什么块(然后 else )将导致循环的结束,这使得它再次成为

另一个选择是:

Action randNum = 
    () => {
              num03 = rand.Next(1, 11);
              num04 = rand.Next(1, 11);
          };

并在你的循环中:

while(true)
{
     Console.Write("What is: " + num03 + " x " + num04 + " = ");
     int answer = Convert.ToInt32(Console.ReadLine());
     if (answer == num03 * num04)
     {
         Console.WriteLine("Correct");
         randNum();
     }
     else
     {
         Console.WriteLine("Incorrect");
     }
}

虽然我认为所有这些对于如此小的这样一个矫枉过正,你可以很好地做到这一点,无论如何我建议如果你实际上做其中一个就是首先一个