好吧,我已经尝试打印和数组,然后使用另一个数组进行反转,但我正在尝试创建一个 For 循环,它将采用一个数组并反转所有元素,而无需我遍历创建全新数组的过程。
我的 for 循环遇到了一些问题,我不知道从这里去哪里...我使用 i 来获取末尾的元素并将其移动到前面,然后 j 被用作一个计数器来跟踪元素...如果有更简单的方法来做到这一点任何建议将不胜感激。
我是这种编程语言的新手,因此非常感谢任何额外的信息。
#include <stdlib.h>
#include <time.h>
int Random(int Max) {
return ( rand() % Max)+ 1;
}
void main() {
const int len = 8;
int a[len];
int i;
int j = 0;
Randomize() ;
srand(time(0));
//Fill the Array
for (i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
//Print the array after filled
for (i = 0; i < len; ++i) {
printf("%d ", a[i]);
}
printf("\n");
getchar();
//Reversing the array in place.
for (i = a[len] -1; i >= 0, --i;) {
a[i] = a[j];
printf("%d ", a[j]);
j++;
}
}
最佳答案
while 循环可能更容易概念化。可以将其视为从两端开始并交换两个元素,直到到达中间。
i = len - 1;
j = 0;
while(i > j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i--;
j++;
}
//Output contents of now-reversed array.
for(i = 0; i < len; i++)
printf("%d ", a[i])
关于c - 原地反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736896/