2013-03-05 20 views
1

嗨,朋友,我有這個數組,我試圖找出有多少元素是重複的,剩下的元素是什麼。但是它顯示出不同結果的問題。請檢查findig重複元素在一個數組中,不工作

#include <stdio.h> 
#include <stdlib.h> 

#define SIZE 30 

int const arr_1[SIZE] = {3,4,3,7,4,90,45,23,57,68,23,14,57, 
        34,20,39,18,3,2,23,45,67,89,68,12,34,56,78,3 
        }; 



int main() 
{ 

    int i,j,yes=0, no=0; 

    for(i=0;i<SIZE;i++) 
    { 
    for(j=0; j<SIZE; j++) 
    { 
     if(arr_1[i] == arr_1[j]) 

       yes++; 
     else 

      no++; 

    } 

    } 

    printf("temp: %d\t Not: %d\n",yes,no); 

    system("PAUSE"); 
    return 0; 
} 
+0

是什麼'temp'? – triclosan 2013-03-05 12:07:00

+3

你認爲'{3,3,3,3}'的結果是什麼? – zch 2013-03-05 12:07:23

+1

什麼是'temp'和'not'? – Aditi 2013-03-05 12:07:38

回答

0

那你tempnot變量?你不使用yesno

其實algorythm必須予以糾正:

for (i = 0; i < SIZE; i++) 
{ 
    int notfound = 0; 
    for (j = i + 1; j < SIZE; j++) 
    { 
     if (arr_1[i] == arr_1[j]) 
     { 
      yes++; 
      notfound = 1; //found, no need to iterate anymore 
      break; 
     } 
    } 
    if (notfound == 0) //and we know that element isn't duplicate only here 
     no++; 
} 
0

的問題是,你兩次比較每個元素對。例如,您正在比較arr_1[1] == arr_1[2],但稍後在循環中,您還會比較arr_1[2] == arr_1[1],因此結果會計數兩次。另外,您將元素i與元素i進行比較,該元素將始終相同。爲了解決這個問題,你應該改變:

for(j=0; j<SIZE; j++) 

for(j=i+1; j<SIZE; j++) 

這樣,第二循環從第一循環的當前索引開始,你只檢查每對一次。

+0

感謝朋友...我知道了 – EmbeddedCrazy 2013-03-05 12:12:07

0
#include <stdio.h> 
    #include <stdlib.h> 

    int arr_1[30] = {3,4,3,7,4,90,45,23,57,68,23,14,57,34,20,39,18,3,2,23,45,67,89}; 
    int main() 
    { 

     int i,j,yes=0; 
     for(i=0;i<23;i++) 
     { 
     yes=0; 

     for(j=0; j<23; j++) 
     { 
      if(i==j){continue;} 
      if(arr_1[i] == arr_1[j]) 
       yes++; 


     } 
     if(yes==0) 
      { printf("\n%d unique element",arr_1[i]); 
       } 
     else 
       { printf("\n%d repeat %d time(s) " ,arr_1[i],yes);} 

     } 



    return 0; 
} 

enter image description here

+0

檢查此代碼它將顯示唯一的編號和重複的號碼。如果你想顯示重複號碼本身。然後初始化yes = 1 – 2013-03-05 12:48:40

相關問題