使用for循环来反转数组无济于事

编程入门 行业动态 更新时间:2024-10-23 17:34:53
本文介绍了使用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循环来反转数组无济于事

本文发布于:2023-06-04 08:34:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/493348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   无济于事

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!