本文介绍了使用for循环来反转数组无济于事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过使用for循环来反转由15个数字组成的数组,但是由于某种原因,数组顺序保持不变.
I am trying to reverse an array of 15 numbers by using a for loop, but for some reason the array order stays the same.
我的代码如下:
int main() { int arr[15] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int i, j, temp; for (i = 0; i < 15; i++) { temp = arr[15 - i - 1]; arr[15 - i - 1] = arr[i]; arr[i] = temp; } j = 0; do { std::cout << arr[j] << " "; j++; } while (j < 15); }知道我做错了什么吗?
推荐答案是的,一旦i超过中点,您将再次交换所有元素.
Yes, you swap all the elements back again once i is past the half-way point.
要扭转,您只需要走一半即可;即将i设置为15/2.
To reverse, you only need to go half way; i.e. run i to 15 / 2.
更多推荐
使用for循环来反转数组无济于事
发布评论