c# - 我如何总结每 5 个数字而不是所有数字?

标签 c# loops sum numbers

我需要一些关于 for 循环的帮助。我试图将我输入的每五个数字相加,而不是将它们全部相加。我需要更改什么?

        int count = 0;
        double total = 0;

        Console.Write("Enter your number: ");
        int input = int.Parse(Console.ReadLine());

        while (input != 0)
        {
            count++;
            for (count = 0; count <= 0; count += 5)
            {
                total = total + input;
            }
            Console.Write("Enter your number: ");
            input = int.Parse(Console.ReadLine());
        }
        Console.WriteLine("The sum of every +5 numbers is: {0}", total);
        Console.ReadKey();

最佳答案

假设您输入一个数字列表,并添加第一个数字和之后的每五个数字(因此第 1、第 6、第 11 等):

int count = 0;
double total = 0;

Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());

while (input != 0)
{
    count++;
    if (count % 5 == 1)
        total = total + input;
    Console.Write("Enter your number: ");
    input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();

这通过使用模运算符 (%) 来实现。模运算符返回涉及您指定数字的除法运算的余数

在代码if (count % 5 == 1)中,问题是:

Is the remainder of count divided by 5 equal to 1?

如果是这样,它会添加数字。如果不是,则跳过

余数为一的原因是因为我们想要结果 1、6、11 等:

1 / 5 = remainder 1
6 / 5 = remainder 1
11 / 5 = remainder 1

如果您将模值更改为 0,它将返回位置 5、10、15 等处的结果。

关于c# - 我如何总结每 5 个数字而不是所有数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58302242/

相关文章:

C# - 使用标记识别值的子串求和

c# - 获取字节子数组

c# - 需要在 C# 中为数字编写正则表达式

php 执行无限循环

r - 循环遍历列并返回值

javascript - 循环遍历 Mongoose 对象

MYSQL SUM 语法

javascript - 通过电线将数据从 js 发送到 Controller

javascript - 无法从 javascript 访问 ViewBag(有一个 JSON 对象列表)

javascript - JavaScript 中的 SUMIF() ?