如何使WHILE循环工作?

时间:2016-05-28 23:25:06

标签: c# loops if-statement while-loop do-while

目前正在做一个我认为我做得对的练习,使用IF ELSE语句,但是一旦提交,我被告知使用WHILE或DO-WHILE循环,我遇到了一些麻烦。你会看到我在哪里使用WHILE循环,但它给了我一个无限循环的错误信息,我分配给它,我不知道如何让它停止!

static void Main(string[] args)
    {
        decimal hours;
        const decimal HOURLY_RATE = 2.5m;
        const decimal MAX_FEE = 20.00m;
        Console.WriteLine("Enter the amount of hours parked:");
        hours = decimal.Parse(Console.ReadLine());
        decimal parkingCost = hours * HOURLY_RATE;

        while (hours < 1 || hours > 24) 
        {
            Console.Write("Enter correct amount of hours - 1 to 24. ");
        }

        if (parkingCost > MAX_FEE) 
        {
            Console.Write("Total fee is $" + MAX_FEE);
            Console.WriteLine(" Time parked in hours is " + hours);
        }
        else
        {
            parkingCost = hours * HOURLY_RATE;
            Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
            Console.WriteLine("Time parked in hours is " + hours);
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

所以想法是我想要输入“正确的小时数 - 1到24”来显示用户输入的数字是否小于1或大于24,否则程序将继续使用IF和ELSE语句。

2 个答案:

答案 0 :(得分:0)

您忘记再次读取while循环中的值以获取新值:

    while (hours < 1 || hours > 24) 
    {
        Console.Write("Enter correct amount of hours - 1 to 24. ");
        Console.WriteLine("Enter the amount of hours parked:");
        hours = decimal.Parse(Console.ReadLine());
    }

或者作为一个Do虽然你可以摆脱第一次读取并且只有错误循环

do {
   Console.WriteLine("Enter the amount of hours parked:");
   try{
     hours = decimal.Parse(Console.ReadLine());
     if(hours <1 || hours > 24) 
        Console.Write("Enter correct amount of hours - 1 to 24. ");
   } 
   catch { Console.WriteLine("Please enter a valid numeric value"); }
} while(hours < 1 || hours > 24);

我添加了try catch,因为如果他们输入的值不是数字,则会引发错误。

答案 1 :(得分:0)

只需在while循环中添加接受输入的行,如下所示

static void Main(string[] args)
{
    decimal hours;
    const decimal HOURLY_RATE = 2.5m;
    const decimal MAX_FEE = 20.00m;
    Console.WriteLine("Enter the amount of hours parked:");
    hours = decimal.Parse(Console.ReadLine());
    decimal parkingCost = hours * HOURLY_RATE;

    while (hours < 1 || hours > 24) 
    {
        Console.Write("Enter correct amount of hours - 1 to 24. ");
        hours = decimal.Parse(Console.ReadLine());
    }


    parkingCost = hours * HOURLY_RATE; // to recalculate

    if (parkingCost > MAX_FEE) 
    {
        Console.Write("Total fee is $" + MAX_FEE);
        Console.WriteLine(" Time parked in hours is " + hours);
    }
    else
    {
        parkingCost = hours * HOURLY_RATE;
        Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
        Console.WriteLine("Time parked in hours is " + hours);
    }
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey();
}

}