You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组逆序输出实现求助:现有代码仅输出原数组

Fixing Your Array Reversal Issue

Hey Tyler, I see exactly where the problem is! Right now, your code is doing tempArray[i] = A[i] inside that reverse loop—which just copies each element from the original array to the same position in the temp array. No wonder it's printing the original array instead of the reversed one!

You were spot-on about needing two indices: one to track the decreasing position in the original array (starting from the last element) and another to track the increasing position in the temp array (starting from the first element). Here's how to implement that smoothly:

Corrected Code

static void reverseArray(int [] A) {
    int[] tempArray = new int[A.length]; // Use A.length instead of hardcoding 10 for flexibility
    // Use two indices to map original array's end to temp array's start
    for(int originalIndex = A.length - 1, tempIndex = 0; originalIndex >= 0; originalIndex--, tempIndex++) {
        tempArray[tempIndex] = A[originalIndex];
    }
    printArray(tempArray); // Print the properly reversed temp array
}

Breakdown of the Fix

  • We swapped the hardcoded 10 with A.length so the method works for any size array, not just 10 elements (a solid practice for reusable code!).
  • The for loop now uses two variables in sync:
    • originalIndex starts at the last element of A (A.length - 1) and counts backward.
    • tempIndex starts at the first element of tempArray (0) and counts forward.
  • Each iteration takes the current end element from A and drops it into the current start position of tempArray—this is what actually flips the order of elements!

Alternative Approach (Single Index)

If you prefer a simpler loop structure with just one index, you can calculate the reversed position mathematically:

static void reverseArray(int [] A) {
    int[] tempArray = new int[A.length];
    for(int i = 0; i < A.length; i++) {
        // Grab the element from the opposite end of the original array
        tempArray[i] = A[A.length - 1 - i];
    }
    printArray(tempArray);
}

This works because for each index i in the temp array, we pull the element from A that's at the mirror position (e.g., when i=0, we take A[9] for a 10-element array; when i=1, we take A[8], and so on).

Either way, both approaches create a reversed copy of the original array without modifying A itself—exactly what you needed!

内容的提问来源于stack exchange,提问作者Tyler P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:52:04