C语言 如何检查数组中的数字是否相等?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20721554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:31:57  来源:igfitidea点击:

How to check if numbers in array equal?

carrays

提问by Alon

How do you check if numbers in an array are equal? I have an array with 10 numbers, and I want to check if two or more of the numbers are equal. What is the best way to check this? Thanks.

如何检查数组中的数字是否相等?我有一个包含 10 个数字的数组,我想检查两个或多个数字是否相等。检查这个的最好方法是什么?谢谢。

回答by Pranav Jituri

You can solve this question using the following program of linear search. The following program will not only report the array elements which are equal but also the number of array elements which are equal. Incase any mistakes please let me know :)

您可以使用以下线性搜索程序来解决这个问题。下面的程序不仅会报告相等的数组元素,还会报告相等的数组元素的数量。如果有任何错误,请告诉我:)

#include <stdio.h>

int main()
{
    int a[10], i, j, flag = 0;

    printf("Please Enter 10 Numbers");

    for(i = 0; i < 10; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < 10; i++)
    {
        for(j = i + 1; j < 10; j++)
        {
            if(a[i] == a[j])
            {
                flag++;
                printf("Array Element %d and %d are equal", i, j);
            }
        }
    }

    printf("\nThe Equal Numbers In The Array Are = %d", flag);
    return 0;
}

回答by rullof

If you are with 1D array, you have to loop through each element, then check for each equal with an index bigger to prevent duplicating the result because (arr[i]==arr[j] => arr[j]==arr[i]).

如果您使用一维数组,则必须遍历每个元素,然后检查每个具有更大索引的相等以防止重复结果,因为(arr[i]==arr[j] => arr[j]==arr[i]).

#include <stdio.h>

int main()
{
    int i, j, dup=0;
    int arr[10] = { 4, 7, 2, 4, 3, 1, 7, 9, 6, 5};
    for(i = 0; i < 10; i++){
        for(j = i + 1; j < 10; j++){
            if(arr[i] == arr[j]){
                printf("arr[%d] = %d = arr[%d] = %d\n", i, arr[i], j, arr[j]);
                dup++;
            }
        }
    }
    printf("\nnumber of duplicates is %d\n", dup);
    return 0;
}

回答by haccks

For an unsorted array, it is better to sort the array first. I used the qsortfunction to sort the array. After sorting the array, I compare the adjacent element for each of the element.

对于未排序的数组,最好先对数组进行排序。我使用该qsort函数对数组进行排序。对数组进行排序后,我比较每个元素的相邻元素。

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10


int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int main()
{
   int values[] = { 88, 56, 100, 2, 100, 56, 56, 56, 2, 1 };
   int count = 0;
   qsort(values, 5, sizeof(int), cmpfunc);

   for( int i = 0 ; i < SIZE-1; i++ )
   {
      if(values[i] == values[i+1])
        count++;
   }
   printf("%d dupes", count);

   return(0);
}