我一直试图让这个工作几天,我仍然无法弄清楚错误。当我输出代码时,它会打印,但是它不会找到友好的对(第一个=第二个除数,反之亦然)。
#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 );
}
答案 0 :(得分:6)
您没有在代码中为total指定任何值:
int sumDivisors( int num )
{
int counter, total;
for( counter = 1; counter < num; counter++ )
{
if( num % counter == 0 )
{
total += counter;
}
}
return ( total );
}
所以它包含垃圾不可预测的值!
应该是:int counter, total = 0;