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

如何对二维数组中奇数索引列的元素求和?

解决二维数组奇数索引列求和问题

要实现仅对奇数索引列(索引从0开始,即第2、4……列)的元素求和,核心是在求和时获取列的索引并判断是否为奇数。你原来用增强for循环无法拿到列索引,所以需要改成带索引的嵌套循环,具体修改如下:

修改后的完整代码

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int row, col, sum;
    row = sc.nextInt();
    col = sc.nextInt();

    sum = 0;

    int[][] a = new int[row][col];

    // 生成二维数组
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[i].length; j++) {
        a[i][j] = i + j + 1;
      }
    }

    // 输出二维数组
    for (int[] rows : a) {
      for (int item : rows) {
        System.out.print(item + " ");
      }
      System.out.println();
    }

    // 仅对奇数索引列求和
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[i].length; j++) {
        // 判断列索引是否为奇数(索引从0开始)
        if (j % 2 == 1) {
          sum += a[i][j];
        }
      }
    }

    System.out.print("sum of odd index columns=" + sum);

    sc.close();
  }
}

关键修改点

  • 将原来的增强for求和循环替换为带行索引i和列索引j的普通嵌套循环,这样能获取到每一列的索引值
  • 添加判断条件 if (j % 2 == 1):因为索引从0开始,奇数索引对应第2、4……列,满足条件时才将该元素加入求和变量sum
  • 调整输出语句的提示文本,更清晰地区分全元素求和与奇数列求和

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:45:13