将连续数字添加到限制,显示迭代次数

时间:2015-12-06 09:27:36

标签: c#

我正在通过本书学习C#,并希望得到一些帮助。我想创建一个控制台程序,将连续的数字加在一起,直到总数达到用户定义的限制。然后程序将计算并显示执行的迭代次数。

这是书中所述的练习:

  

在生日蛋糕中,人们过去常常放几根蜡烛作为庆祝的年数。假设蜡烛以x件的方式出售。现在假设一个新生儿收到了他的第一盒生日蜡烛。写一个程序,告诉你在购买新蜡烛盒需要多少生日之后

编辑:它现在有效 - 下面是新代码。

using System;
class Program
{
    static void Main(string[] args)
    {
        int x, y = 0, z = 0, a = 0;

        Console.WriteLine("This program will calculate when you have to buy a new box of candles.");
        Console.WriteLine("Enter the number of candles the box contains: ");
        x = Convert.ToInt32(Console.ReadLine());

        while (x > 0)
        {
            z = z + 1;
            a = a + z;

            y = x - a;

            if (y <= z)
            {
                break;
            }
        }

        Console.WriteLine("After {0} years you have to buy a new box of candles.", z);
        Console.ReadLine();
    }
}

2 个答案:

答案 0 :(得分:0)

这可以解决您的问题:

对于20支蜡烛的例子,循环后count_birthdays将 6 ,因为前5个生日需要1 + 2 + 3 + 4 + 5 = 15支蜡烛,所以你赢了已经为第六次留下了足够的空间。

int count_birthdays = 0;
int used_candles = 0;
while (used_candles <= candles)
{
    count_birthdays++;
    used_candles = used_candles + count_birthdays;
}

答案 1 :(得分:-1)

提示可能会有一个“break”关键字,可让您退出循环。

此外,当您进入'while'循环时,您可能会发现这是表达解决方案的更好方式。现在,查看'break'