C 中查找数组中唯一元素的问题

问题描述 投票:0回答:1

我需要打印整数数组中的所有唯一元素,但是当我编译程序时出现以下错误。

muratakar$ gcc Code.c 
    Code.c:20:39: error: expected expression
    int isUnique = uniqueElements(arr[], n);

这是我的代码,如下所示。请帮助我找到问题并解决它。预先感谢。

//Unique Elements Finder : Implement a C function to find all unique elements in an array.

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

int uniqueElements(int arr[], int n);
int main()
{
    system("clear");
    int arr[10];
    
    for(int i=0;i<10;++i)
    {
        printf("Please enter a number: ");
        scanf("%d", &arr[i]);
    }

    int n;
   
    int isUnique = uniqueElements(arr[], n);
    printf("\n\n");
    return 0;
}

int uniqueElements(int arr[], int n)
{
    for (int i = 0; i < n;++i)
    {
        int isUnique = 1;
        for (int j = 0; j < n;++j)
        {
            if(i!=j && arr[i]==arr[j])
            {
                isUnique = 0;
                return 0;
            }
        }
        if (isUnique)
        {
            printf("%d", arr[i]);
        }
    }
}```

I tried to put `10` between [] but it did not help.                                                                                                                      

arrays c function unique
1个回答
-1
投票

将任务分成更小的问题。

这里有一个“暴力”实现的例子:

int isUnique(const int *array, const int val, const size_t size)
{
    size_t count = 0;
    for(size_t index = 0; index < size; index++)
    {
        //if found more than once the it is not unique
        if((count += (array[index] == val)) > 1) break;
    }
    return count == 1;
}

void printAllUnique(const int *array, size_t size)
{
    for(size_t index = 0; index < size; index++)
        if(isUnique(array, array[index], size))
            printf("Unique value %d at pos %zu\n", array[index], index);
}

编译错误:您只需要使用数组的名称:

int isUnique = uniqueElements(arr, n);
© www.soinside.com 2019 - 2024. All rights reserved.