【发布时间】:2019-11-20 04:17:23
【问题描述】:
C语言
我想比较一个数组和它的反转形式并检查它是否相同。
例如,arr1 = 5 5 8 8 5 5
反向 arr1 = 5 5 8 8 5 5
那么输出将是: Array is the same in reverse.
由于某种原因,当我尝试比较我的两个数组时,它总是说它是相同的,即使它不是。
例如:输入 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;
}
【问题讨论】:
-
这段代码有这么多错误,首先你需要的数组大小是多少? size = sizeof(arr) 将返回数组指针的大小,取决于机器可能是 4 或 8。输入部分在哪里?然后在反转数组时,您将覆盖原始数组。最后, if (temp = arr[j]) 总是返回 true,因为它是赋值,而不是比较。您可能需要 if (temp == arr[j]) 但这在逻辑上也没有意义。
标签: c arrays linux compare string-comparison