首页 > 解决方案 > 在循环中添加所有商

问题描述

我正在尝试为我的程序的一部分添加所有商的总数。如果一个数字可以在一定范围内整除并加上商的总和,下面的部分应该打印出来。我创建了一个变量来存储总数,但是当它打印出来时,它只打印出每个单独的商而不是总和。我认为问题在于我在哪里实施总计,但我不确定。

            //loop through number 1-25 and find which numbers are divisable
            for (int divisor = 1; divisor <= 25; ++divisor)
            {
                int quotient = dividend / divisor;

                if (dividend % divisor == 0)
                {
                    int sumOfQuotients = 0;
                    Console.WriteLine($"{dividend} is divisible by {divisor} ({quotient})");
                    sumOfQuotients += quotient;
                    Console.WriteLine($"The sum of the quotients is {sumOfQuotients}");
                }

标签: c#

解决方案


sumOfQuotients将循环之前的初始化和结果的写入移到之后:

var dividend = 10;
int sumOfQuotients = 0;
//loop through number 1-25 and find which numbers are divisable
for (int divisor = 1; divisor <= 25; ++divisor)
{
    int quotient = dividend / divisor;
    if (dividend % divisor == 0)
    {
        Console.WriteLine($"{dividend} is divisible by {divisor} ({quotient})");
        sumOfQuotients += quotient;
    }
}
Console.WriteLine($"The sum of the quotients is {sumOfQuotients}");

现场示例:https ://dotnetfiddle.net/Rsfu7r


推荐阅读