gpt4 book ai didi

c - 使用循环查找除数

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:53 25 4
gpt4 key购买 nike

我为以下程序编写了代码,但我不明白如何涉及一个函数。这个问题要求我使用一个返回除数之和的函数。请查看问题和我的代码,并尝试帮助我。

问题:

Write a C program that finds and prints the sum of divisors for all the numbers between 101 and 110. The divisors of x are those numbers x divides without a remainder (e.g. the divisors of number 10 are 1, 2, 5, and 10 and their sum = 1+2+5+10=18, the divisors of number 11 are 1 and 11 and their sum=1+11=12, and so forth). Your program should also print the number (101 to 110) that has the maximum sum of divisors.

Your program should use at least one function called div_sum that takes a number and returns its sum of divisors.

我的代码:

#include <iostream>
#include <stdio.h>


int main()

{
int i=1, x=101, sum, smax=0, xmax=0;

for (x=101; x<=110; x++)
{ sum=0;

for(i=1; i<=x; i++)
{
if(x%i==0)
sum+=i;
}

if(sum>smax)
{
smax=sum;
xmax=x;
}

printf("The sum of factors of %d = %d\n",x,sum);

}

printf("The number that has the maximum sum of divisors is %d with the sum of %d",xmax,smax);

return 0;
}

最佳答案

您可以将计算每个 x 的除数之和的循环移动到 separate 函数:

int div_sum(int x) {
int sum = 0;
for(int i=1; i<=x; i++)
{
if(x%i==0)
sum+=i;
}
return sum;
}

并在你的程序中使用它:

for (x=101; x<=110; x++)
{
sum= div_sum(x);
if(sum > amax)
...
}

关于c - 使用循环查找除数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20977594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com