我一直试图让这个工作几天,我仍然无法找出错误。当我输出代码时,它会打印,但它不会找到友好的对(第一个==秒的除数,反之亦然)。C程序错误 - 输出0
#include <stdio.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
int sumDivisors(int num);
int sumDivisors(int num)
{
int counter, total;
for(counter = 1; counter < num; counter++)
{
if(num % counter == 0)
{
total += counter;
}
}
return (total);
}
int main(void)
{
int higher, lower, lowx, lowy, x, y, numOfPairs = 0;
printf("This program finds all amicable numbers within a range. \n");
printf("Please enter a lower limit: \n");
scanf("%d", &lower);
printf("Please enter a higher limit: \n");
scanf("%d", &higher);
for(lowx = lower; lowx <= higher; lowx++)
{
for(lowy = lower; lowy <= higher; lowy++)
{
if(sumDivisors(lowx) == sumDivisors(lowy))
{
numOfPairs++;
printf("Pair #%d: (%d, %d)\n", numOfPairs, lowx, lowy);
}
}
}
printf("There are %d amicable pairs from %d to %d\n", numOfPairs, lower, higher);
system("pause");
return (0);
}
考虑写内环为'为(洛伊= lowx + 1;洛伊<=更高;洛伊++)',以避免重复。 –
好点,它使它更有效率。谢谢! – Submersed24
在进一步思考时,你可能误解了友好数字的定义,它是[两个不同的数字,因此每个数字的正确除数的和等于另一个数字](https://en.wikipedia.org/维基/ Amicable_numbers)。您可以在[OEIS - A063990](http://oeis.org/A063990)上找到第一对清单。看看这个[Q&A](http://stackoverflow.com/a/28268160/4944425)进行更有趣的优化。 –