我正在研究一个示例问题,它要求我检查用户输入的数组是否对称。我已经弄清楚如何通过创建另一个数组,以相反的顺序复制第一个数组,然后检查它们是否彼此相等来做到这一点。如下面的代码所示。
#include <stdio.h>
int main(void){
#define NUM_ELEMENTS 12
int userArray[NUM_ELEMENTS];
int userArray2[NUM_ELEMENTS];
int i;
int tempVal = 0;
double sumArray = 0;
double aveArray = 0;
printf("Enter 12 interger numbers (each one separated by a space):\n");
for(i = 0; i < NUM_ELEMENTS; i++){
scanf_s("%d", &userArray[i]);
}
for(i = 0; i < NUM_ELEMENTS; i++){
sumArray = sumArray + userArray[i];
}
aveArray = sumArray/NUM_ELEMENTS;
printf("\nAverage of all data points is %.2lf \n",aveArray);
printf("\nAn array in reverse order:\n");
for(i = NUM_ELEMENTS - 1; i >= 0; i--){
printf("%d ",userArray[i]);
}
printf("\n");
//Used swap values in the array
for(i = 0; i < (NUM_ELEMENTS / 2); i++){
tempVal = userArray[i];
userArray2[i] = userArray[NUM_ELEMENTS - 1- i];
userArray2[NUM_ELEMENTS - 1 - i] = tempVal;
}
if(userArray[i] == userArray2[i])
printf("\nThis array is symmetric\n");
else
printf("\nThis array is NOT symmetric\n");
return 0;
}
因此,如果用户输入 1 2 3 4 5 6 6 5 4 3 2 1,程序将返回该数组是对称的。
我只是好奇是否有更简单的方法可以做到这一点?
只需同时向前和向后迭代即可:
// i iterates forwards from the start
// j iterates backwards from the end
// once they pass each other, we're done.
for (int i = 0, j = NUM_ELEMENTS - 1; i < j; i++, j--) {
if (userArray[i] != userArray[j]) {
printf("\nThis array is not symmetric\n");
return 0; // No point in running this function any longer at this point.
}
}
// If the function didn't return in the for loop, the array is symmetrical.
printf("\nThis array is symmetric\n");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)