数组中没有重复值

时间:2018-10-31 09:30:52

标签: c

我需要制作一个将数字存储在数组中的程序。但是它必须没有重复的元素。

  int x;
  int z[8];

  for( x = 0; x<8;x++) 
      printf("number: ");
      scanf("%d",&z[x]);
  }

  for( x=0;x<8;x++) {
    printf("%d ",z[x]); 
  }

2 个答案:

答案 0 :(得分:0)

首先,初始化数组,以免最终读取未初始化的值并使测试失败。

int user_nums[6] = {0};

接下来,您需要在for循环中再进行一次检查,以便再次读取该数字(如果该数字重复)。

代码将如下所示。

#include<stdio.h>
int main(){
    int x,y;
    int exists = 0;
    int user_nums[6] = {0};
    for( x = 0; x<6;x++){//for loop  to get the players selected numbers    

        do {
            exists = 0;
            printf("Enter a number(from the #'s 1-42): ");
            scanf("%d",&user_nums[x]);

            for(y =0; y < x; y++) { //to check for duplicates
                if (user_nums[x] == user_nums[y])
                {   
                    printf("Number already exists\n ");
                    exists = 1;             
                    break;
                }
            }

        }while (user_nums[x]<1 || user_nums[x]>42 || exists);//accepts only numbers from 1-42 which are not duplicates (continous to ask you for a number until condition is met).
    }

    printf("Your numbers: \n");

    for( x=0;x<6;x++){
        printf("%d ",user_nums[x]); // prints the numbers you inputed.
    }

    return 0;
}

答案 1 :(得分:0)

以下code可以在O(n)中工作:

#include<stdio.h>

int main()
{
    int user_nums[6];
    int index[50];

    for (int i = 0; i != sizeof(index) / sizeof(index[0]); ++i)
        index[i] = -1;

    for (int i = 0; i < sizeof(user_nums) / sizeof(user_nums[0]); ++i) {
        for (;;) {
            printf("Enter a number(from the #'s 1-42): ");
            scanf("%d", user_nums + i);
            if (user_nums[i] < 1 || user_nums[i] > 42) {
                printf("wrong number\n");
                continue;
            }
            if (index[user_nums[i]] != -1) {
                printf("dump number\n");
                continue;
            }
            index[user_nums[i]] = i;
            break;
        }
    }

    printf("Your numbers: \n");

    for(int i = 0; i < 6; ++i)
        printf("%d ", user_nums[i]);

    return 0;
}