c# - 在循环中添加所有商
问题描述
我正在尝试为我的程序的一部分添加所有商的总数。如果一个数字可以在一定范围内整除并加上商的总和,下面的部分应该打印出来。我创建了一个变量来存储总数,但是当它打印出来时,它只打印出每个单独的商而不是总和。我认为问题在于我在哪里实施总计,但我不确定。
//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}");
}
解决方案
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}");
推荐阅读
- html - 如何在 HTML 页面中并排放置两个 div
- javascript - Slick Slider No Longer Scaling
- android - WebRTC: Undefined reference to "__real_malloc" in Android project linking with WebRTC library
- php - Can't read data that send from controller to view by foreach
- javascript - Some images break on load
- angular - 错误错误:未捕获(承诺):NullInjectorError:StaticInjectorError(AppModule)[FormBuilder]
- python - 在 BigQuery 中将日期格式从“month_name day,year”转换为“yyyy-mm-dd”
- web-scraping - Beautiful Soup,抓取拍卖网站,在拍卖完成后清除已售物品 div
- r - if/then 替换在 R 中以列值为条件的行上循环的值
- spring-integration - 如何将原始消息存储到 JMS 队列而不是 org.springframework.messaging.MessageDeliveryException 表单中