首页 > 解决方案 > 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();

标签: c#while-loop

解决方案


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;
    }
}

推荐阅读