c# - C# 无限循环。如何应用循环控制变量?
问题描述
namespace QueenslandRevenue
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Number of contestants last year?>> ");
int contestLast = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number of contestatnts this year?>> ");
int contestThis = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(contestThis + contestLast);
Console.ReadLine();
正在尝试一项任务。我知道我需要添加一个循环控制变量,但我不确定该怎么做。任何指针将不胜感激。
const int MAX = 30;
const int MIN = 0;
while (contestLast > MAX || contestLast < MIN || contestThis > MAX || contestThis < MIN)
{
Console.WriteLine("Please enter valid number of contestants");
}
Console.ReadLine();
解决方案
在static void Main(string[] args)
方法内部,添加一个 while 循环,该循环将一直运行,直到用户输入有效输入。当他这样做时,您会将布尔变量更改stop
为 true,以便执行将中断循环。
int MAX = 30;
int MIN = 0;
bool stop = false;
while (!stop)
{
Console.WriteLine("Number of contestants last year?>> ");
int contestLast = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number of contestatnts this year?>> ");
int contestThis = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(contestThis + contestLast);
Console.ReadLine();
if (contestLast > MAX || contestLast < MIN || contestThis > MAX || contestThis < MIN)
{
Console.WriteLine("Please enter valid number of contestants");
Console.ReadLine();
}
else
{
stop = true;
}
}
推荐阅读
- python - 当 Python 中的字符串更改时,字符串 id 不会更改。将字符添加到字符串的复杂性
- javascript - array.map() 中花括号的含义
- python - 用射击法求解自然对流方程(热量和流动)
- python - 如何将用户输入与python中json文件中的多个目录进行比较
- ssl - 如何将我当前的 SSL 证书添加到任何新的子域?
- java - Spring ws - 每个属性都返回 null
- python - Django - objects.get 返回什么
- vba - 将方法添加到类的属性
- html - Apple Touch Icon - 是否允许使用 .ico 文件?
- python - 根据最大值覆盖数据帧中的数据