【问题标题】:Entering numbers from a specific range and adding them up when their sum reaches a 5-digit number输入特定范围内的数字,当它们的总和达到 5 位数字时将它们相加
【发布时间】:2020-08-14 15:30:24
【问题描述】:

我对 C# 还很陌生。我的编程老师给了我以下问题:我必须编写一个程序,让您输入特定范围/区间的数字(他给我的范围是从 10 到 10,000,但您可以自己考虑)。

我必须使用“while”或“do-while”循环来完成。到目前为止,这是我到达的地方:

int n, Sum = 0;
        while ((Sum < 10000))
        {
            Console.Write("Type in a number from the interval [10; 9999]: ");
            n = int.Parse(Console.ReadLine());
            if ((n <= 10) || (n >= 9999))
                {
                Console.WriteLine("That number isn't in the range!");
                Console.Write("Type in a number from the interval [10; 9999]");
                n = int.Parse(Console.ReadLine());

我已经完成了一半,但是当总和达到 5 位数字时,我不知道如何让程序将它们相加。提前致谢!

【问题讨论】:

  • n 是有效数字(在区间内)时,执行Sum += n;

标签: c# while-loop do-while


【解决方案1】:

您需要将n 添加到Sum

因此,不要使用第二个 n = int.Parse(Console.ReadLine());(实际上并没有做任何有用的事情,它只是重复您之前执行的检查),而是使用 Sum += n;

+=Sum = Sum + n 的缩写。

【讨论】:

    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多