2013-03-05 87 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