[C/JAVA]二维数组
C
//计算每个学生成绩,并求和,计算平均数 #include <stdio.h> void main() { int scores[][4] = { //不足4个元素,用0补充 {100, 99, 98, 99,}, {78, 86, 77,}, {43, 56}, {} }; int sum = 0, i, j; for (i = 0; i < 4; ++i, sum = 0) { for (j = 0; j < 4; ++j) { printf("%4d", scores[i][j]); sum += scores[i][j]; } printf(" sum = %4d average = %4.1f\n", sum, sum / (j+.0)); } }
结果:
100 99 98 99 sum = 396 average = 99.0 78 86 77 0 sum = 241 average = 60.2 43 56 0 0 sum = 99 average = 24.8 0 0 0 0 sum = 0 average = 0.0
JAVA
public class TwoDimenArray { public static void main(String[] args) { int[][] scores= new int[][] { //ragged array,不会自动用0填充 new int[] {89, 90, 100, 94, 99}, new int[] {56, 60, 61}, new int[] {103, } }; //或者 // int[][] scores= new int[3][]; // scores[0] = new int[] {89, 90, 100, 97}; // scores[1] = new int[] {56, 60}; // scores[2] = new int[] {103, 99, 101}; int sum = 0; int i, j; for ( i = 0;i < scores.length; ++i, sum = 0 ) { //计算新一组和,把sum调成0 for ( j = 0; j < scores[i].length; ++j ) { System.out.printf( "%4d", scores[i][j] ); sum += scores[i][j]; } System.out.print(" Sum = " + sum + " Average = " + sum / (j + .0)); System.out.println(); } } }
运行结果
89 90 100 94 99 Sum = 472 Average = 94.4 56 60 61 Sum = 177 Average = 59.0 103 Sum = 103 Average = 103.0