2016-09-20 85 views
0

我一直試圖讓這個工作幾天,我仍然無法找出錯誤。當我輸出代碼時,它會打印,但它不會找到友好的對(第一個==秒的除數,反之亦然)。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); 
} 
+0

考慮寫內環爲'爲(洛伊= lowx + 1;洛伊<=更高;洛伊++)',以避免重複。 –

+0

好點,它使它更有效率。謝謝! – Submersed24

+0

在進一步思考時,你可能誤解了友好數字的定義,它是[兩個不同的數字,因此每個數字的正確除數的和等於另一個數字](https://en.wikipedia.org/維基/ Amicable_numbers)。您可以在[OEIS - A063990](http://oeis.org/A063990)上找到第一對清單。看看這個[Q&A](http://stackoverflow.com/a/28268160/4944425)進行更有趣的優化。 –

回答

6

您還沒有給予任何價值在你的代碼以總價:

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;

+1

哦,天哪......謝謝.. 。你救了我,我被用來歸零0 – Submersed24

+0

@ Submersed24它與null爲零有什麼關係? – immibis

+0

我曾經認爲變量默認爲0,所以你不需要將它們設置爲零 – Submersed24