简体   繁体   English

在 C 中输入数组并检查相同的值

[英]Input Array in C and check for same values

how I can input an array of integers and check if 2 pairs of values are equal and I also want to remove the duplicated to have only 1 same value in array?如何输入一个整数数组并检查 2 对值是否相等,并且我还想删除重复的值以在数组中只有 1 个相同的值? I want to print the final result of the array without the duplicated values in it.我想打印没有重复值的数组的最终结果。 I have something like this in mind:我有这样的想法:

int a[SIZE], i;
 printf("Enter %d numbers:\n", SIZE);
 for (i = 0; i < SIZE; i++) {
  scanf_s("%d", a[i]);
 if(i>=1){
  if(a[i-1]==a[i]){
  a[i-1]==a[i];
  printf("%d", a[i-1]);
 }
}

this result gives me what I need but not completely.这个结果给了我我需要的但不完全的。 can you assist with this?你能帮忙吗?

Code代码

#include<stdio.h>
int main() {
   int arr[20], i, j, k, size;
   printf("\nEnter array size:");
   scanf("%d", &size);
   printf("\nEnter Numbers:");
   for (i = 0; i < size; i++)
      scanf("%d", &arr[i]);
   printf("\nList of Unique Numbers:");
   for (i = 0; i < size; i++) {
      for (j = i + 1; j < size;) {
         if (arr[j] == arr[i]) {
            for (k = j; k < size; k++) {
               arr[k] = arr[k + 1];
            }
            size--;
         } else
            j++;
      }
   }
   for (i = 0; i < size; i++) {
      printf("%d ", arr[i]);
   }
}

Explanation解释

After inputting, we start from the first element.输入后,我们从第一个元素开始。 Then within that for loop, we have another for loop to check elements after that element.然后在那个 for 循环中,我们有另一个 for 循环来检查该元素之后的元素。 If there is a duplicate, I remove it.如果有重复,我将其删除。 Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM