【问题标题】:How do i implement an until loop in c#如何在 C# 中实现直到循环
【发布时间】:2021-02-08 17:51:42
【问题描述】:

我正在制作一个简单的高低游戏,我希望游戏继续进行,直到猜到正确的数字或​​猜者想要重新开始。我使用什么循环以及如何实现它

我的代码是

Random RandomNumber = new Random();
int RandomNumber2 = RandomNumber.Next(1, 5);
//Console.WriteLine(RandomNumber2);

//want to insert loop here and it should end when the third else if is done

Console.WriteLine("Make Your Guess Now");
string UserInput = Console.ReadLine();
int UserInput2 = Convert.ToInt32(UserInput);

if (UserInput2 > RandomNumber2)
{
    Console.WriteLine("Your Number is to high");
}
else if (UserInput2 < RandomNumber2)
{
    Console.WriteLine("Your Number is too small");
}
else if (UserInput2 == RandomNumber2)
{
    Console.WriteLine("Congrats on guessing the right number");
}

【问题讨论】:

  • 您可以使用多个构造函数来实现此目的,但在您的情况下,do-while 循环听起来最合适。
  • 在学习传统编程语言时,您会了解变量、类型和条件语句。你学习的下一件事(通常)是关于循环的。使用搜索引擎搜索“looping in c#”,你应该会找到一些教程
  • 最后一个else不需要测试if (UserInput2 == RandomNumber2),因为上面已经处理了其他的可能性,就剩下一个了。即,当这种情况被执行时,UserInput2 总是等于RandomNumber2。请记住,只有在 if 部分未执行时才会执行 else。

标签: c# loops while-loop


【解决方案1】:

执行此操作的标准方法是使用do while loop (C# Reference)

但是在这里,您可以使用无限循环并使用break 语句退出它。这允许您从循环内测试的条件中跳出循环

...
Console.WriteLine("Make Your Guess Now");
while (true) {
    string UserInput = Console.ReadLine();
    int UserInput2 = Convert.ToInt32(UserInput);

    if (UserInput2 > RandomNumber2)
    {
        Console.WriteLine("Your Number is too high. Make another guess");
    }
    else if (UserInput2 < RandomNumber2)
    {
        Console.WriteLine("Your Number is too small. Make another guess");
    }
    else
    {
        Console.WriteLine("Congrats on guessing the right number");
        break;
    }
}

请注意,没有必要在最后一个else中测试UserInput2 == RandomNumber2,因为上面已经处理了其他情况,这是唯一剩下的可能性。请注意,当 if-part 没有执行时才会执行 else-part。

【讨论】:

    【解决方案2】:

    就像说它认为最好的解决方案是

    Do
    {
      --if here
    } While (userinput2==randomnumber2)
    

    【讨论】:

    • c# 区分大小写,只要猜错了他就想重复。因此do { ... } while (UserInput2 != RandomNumber2); 或更好的是while (true),然后在最后一种情况下放置break
    猜你喜欢
    • 2010-10-24
    • 2018-09-21
    • 2010-11-07
    • 2014-02-15
    • 2015-03-11
    • 1970-01-01
    • 2010-09-17
    • 2014-02-04
    • 1970-01-01
    相关资源
    最近更新 更多