Discuss / Java / 作业打卡

作业打卡

Topic source
package com.itranswarp.learnjava;

import java.util.Arrays;

/**
 * 遍历数组
 */
public class Main {
	public static void main(String[] args) {
		int[] ns = { 1, 4, 9, 16, 25 };
		int[] arr = new int[ns.length];
		int m = 0;
		// 倒序打印数组元素:
		for (int n = ns.length - 1; n >= 0; n--) {
			arr[m] = ns[n];
			m++;
		}
		System.out.println(Arrays.toString(arr));
	}
}

你好,请教下,为什么要 -1

int n = ns.length - 1

这个第一次执行是等于3???

int n = ns.length - 1; n >= 0; n--

chenhangaj

#4 Created at ... [Delete] [Delete and Lock User]

不 -1 会 n[5] 溢出
等于  4   ,n-- 一次循环结束后再 -1


  • 1

Reply