c# - 如何在 C# 中限制循环次数

标签 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"));
        }
    }
}

最佳答案

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

关于c# - 如何在 C# 中限制循环次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22019267/

相关文章:

c# - 为 ASP.NET 自定义发布

visual-studio - 如何创建显示在 Web 类别中的 Visual Studio 项目模板?

node.js - 在 Visual Studio 2015 for Angular2 上启动项目

asp.net - 如何在 Visual Studio 2012 中重命名 IIS Express 网站

c# - LINQ where 不接受 1 个或 2 个参数

c# - RestSharp - 如何影响 JSON 序列化(命名)?

c# - 类扩展 - 最佳实践/最佳解决方案

c# - 通过代码添加应用栏(Windows 8.1,C#)

c# - System.Drawing.dll 中出现类型为 'System.ApplicationException' 的未处理异常

c++ - Visual Studio 2013 语法突出显示停止工作