如何在C中反向比较数组是否相同?

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

C语言我想将一个数组与它的反转形式进行比较,并检查它是否相同。

例如arr1 = 5 5 8 8 5 5反转的arr1 = 5 5 8 8 5 5

然后输出将是:数组反向相同。

出于某种原因,当我尝试比较两个数组时,即使不是,也总是说相同。

例如:输入7 8 9。相反的是9 8 7,它与输入的内容不同。但是,我的代码说是。

如何修正比较结果,使结果准确?请指教,谢谢!

我尝试使用goto显示结果。这是我的代码(函数):

void function(int *arr)
{
  int j, c, temp, size;
  size = sizeof(arr);
  int old[size];
  int new[size];

  /*Prints original array from user input*/
  printf("Input Array: ");
  for(j=0; j<size; j++)
  {
     printf("%d ", arr[j]);
     old[j] = arr[j];
  }
  printf("\n");

  /* Reversing the array */
  c = j - 1;
  j = 0;
  while (j < c)
  {
     temp = arr[j];
     arr[j] = arr[c];
     arr[c] = temp;
     j++;
     c--;
  }

  /* Print Reversed Array */
  int i;
  for(i=0; i<size; i++)
  {
     printf("%d ", arr[i]);
     /*saved to new for possible comparison*/
     new[i] = arr[i];
  }
  printf("\n");

  /* Compare original array with reversed array */
  if(temp = arr[j])
  {
     goto same;
  } else {
     goto notsame; 
  }

  same:
     printf("Array is the same in reverse\n");
     return 0;
  notsame:
     printf("Array is not the same in reverse\n");
     return 0;
}
c arrays linux compare string-comparison
2个回答
1
投票

您无法通过sizeof获得数组的大小。您应该打印出大小,然后查看该值将为您提供什么,而不是数组的大小。

您总是得到“相同”的原因是您实际上没有在比较值。您正在将arr [j]分配给temp。 if(temp = arr [j])应该是if(temp == arr [j])。我认为您会发现它不再适用了。

解决此问题的更简单方法是:

void checkReverse(int* arr, int arrSize)
{
   // Loop through the array until you have hit the middle
   for (int i = 0; i < (arrSize - i); i++)
   {
      // Check the element to the element in the same place counting from the back
      if (arr[i] != arr[arrSize - i - 1])
      {
         // If we find any that don't match, we know it's not the same and can return
         printf("Array is NOT the same in reverse.\n");
         return;
      }
   }

   // If we made it this far, they are the same
   printf("Array is the same in reverse.\n");
   return;
}

0
投票

而不是将您要与temp变量进行比较的new[]数组。

  if(temp == arr[j]){
     goto same;
  } else {
     goto notsame; 
  }

用上面的代码替换上面的代码:

for(i=0;i < size ;i++){
  if(old[i] != new[i]){
    goto notsame;
  }
  else if(i == size){
    goto same;
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.