【发布时间】:2015-10-31 02:00:29
【问题描述】:
我有一个程序提示用户输入最多 10 位数字。然后,该程序使用一个函数返回输入的每个数字的除数之和减去自身并显示它,直到该数字等于 1 或 0。我的问题是该函数在 45 的除数相加后停止。我在这里尝试使用递归,因为该函数将被调用 'n' 次,直到每个等于 0 或 1。是什么让递归在这种情况下如此有用,我如何在这里应用它?关于这个函数的调用方式,我有什么遗漏吗?有人可以帮我吗?
例如,
如果用户输入:25 -4 6 45(然后按回车键)
程序应该输出:
25 1 0
-4 0 0
6 6
45 33 15 9 4 3 1 0 0
6 是一个完美数的示例,并且会重复,因此如果出现一个完美数,它应该停止对除数求和。当总和等于 0 时应该打印一次然后停止。 -4 也超出范围,因此它也应该打印 0。必须大于 1。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
//Fields
int i=0, j=0, k=0, l=0, num = 0, x = 0, count = 0, total = 0, z = 0;
signed int b[11] = {0};
char discard;
//Prompt message
printf( "\n\nPlease enter your list of numbers: " );
//This while loop scans until the enter button is pressed
while(i < 11 && (scanf("%d%1[^\n]s", &b[i], &discard)) == 2)
{
++count;
i++;
}
puts("");
puts("");
//Display Factors
while(k <= count)
{
x=b[k];
num = sum_divisors(x);
printf("%d " , num);
k++;
puts("");
}
}//End of main
//function to sum the divisors together
int sum_divisors(int a)
{
int total = 0;
int z = 0;
printf("%d ", a);
if(a < 1)
{
total = 0;
}else
{
if((a%1 == 0) && a !=1)
total = total + 1;
for(z=2; z<102; z++)
{
if((a%z == 0) && a != z)
{
total = total + z;
}//if
}//for
}//end if/else statement
// printf("%d ", total);
return total;
}//end function sum_divisors
【问题讨论】:
-
您标记了greatest-common-divisor。您是否尝试递归地找到 10 个数字的最大公约数并将它们相加?