【发布时间】: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