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

本文关键字:显示 迭代 连续 数字 添加 | 更新日期: 2023-09-27 18:25:46

我正在通过书本自学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();
    }
}

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

这应该可以解决您的问题:

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

一个提示是有一个"break"关键字可以让您退出循环。

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