如何限制循环在C#中的数量

时间:2014-02-25 15:47:53

标签: c# visual-studio

我的代码在每一行“购买”时添加总和,但我只希望他们能够完成5个条目。将此代码复制并粘贴到visual studio中作为控制台应用程序,然后调试或运行它或其他任何东西。我是C#的新手,想知道如何只允许5个数字。我试图不要偏离我下面的代码太远。话虽如此,可能有更先进的方法来做到这一点,但我不希望这样。

namespace SumFiveDoubles
{
    class TotalPurchase
    {
        static void Main()
        {
            double purchase;
            double total = 0;
            string inputString;
            const double QUIT = 0;
            Console.Write("Enter a purchase amount >> ");
            inputString = Console.ReadLine();
            purchase = Convert.ToDouble(inputString);
            while (purchase != QUIT)
            {
                total += purchase;
                Console.Write("Enter another purchase amount or " + QUIT + " to calculate >> "); //I only want this to appear 4 more times\\
                inputString = Console.ReadLine();
                purchase = Convert.ToDouble(inputString);
            }
            Console.WriteLine("Your total is {0}", total.ToString("C"));
        }
    }
}

4 个答案:

答案 0 :(得分:6)

int count = 0;
while (purchase != QUIT && ++count < 5)

答案 1 :(得分:1)

while循环括号内的表达式是其连续条件。如果您不希望循环经过一定数量的迭代,请创建一个迭代计数器,并在计数器超过某个数字时生成一个复合条件false,或purchase变为{ {1}},无论先发生什么。

QUIT

您还可以使用int count = 0; while (purchase != QUIT && count < 5) { ... // Do your stuff count++; } 循环将声明和计数器的增量放在一个位置:

for

答案 2 :(得分:1)

为你添加一个计数器..

        int max = 0;
        while (purchase != QUIT && max < 5)
        {
            total += purchase;
            Console.Write("Enter another purchase amount or " + QUIT + " to calculate >> "); //I only want this to appear 4 more times\\
            inputString = Console.ReadLine();
            purchase = Convert.ToDouble(inputString);
            max++;
        }
        Console.WriteLine("Your total is {0}", total.ToString("C"));

因此,当购买== QUIT或达到最大值时,您的循环将退出。

答案 3 :(得分:0)

您可以使用for-loop

double purchase;
double total = 0;
string inputString;
const double QUIT = 0;

for (int i = 1; i <= 5; i++)
{
    Console.Write("Enter a purchase amount >> ");
    inputString = Console.ReadLine();
    purchase = Convert.ToDouble(inputString);
    if(purchase == QUIT)
        break;

    total += purchase;
    Console.Write("Enter another purchase amount or " + QUIT + " to calculate >> "); //I only want this to appear 4 more times\\
    inputString = Console.ReadLine();
    purchase = Convert.ToDouble(inputString);
}