此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
一格一格的网格
- 2维数组是一个网格:由相同类型的行和列组成。
int g[2][3];创建 2 行 3 列 —— 一共 6 个 int。- 你用两个下标访问一个格子:
g[row][col]。
先行后列(行优先)
- C 把网格一行一行地存:先存完第 0 行,再存第 1 行。
- 要访问每个格子,用一个
for循环遍历行,再在里面用一个for循环遍历列。 g[r][c]是第r行、第c列的格子。两者都从0开始。
传递 2 维数组
- 把网格传给函数时,你必须给出列数:
int g[][3]。 - C 需要列数才能在内存里找到每一行;行数可以留空。
- 所以函数写成
int g[][3], int rows—— 列固定为3,行数则传进来。
English
#include <stdio.h>
int main(void) {
int g[2][3] = {{1, 2, 3}, {4, 5, 6}};
int total = 0;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
total += g[r][c];
}
}
printf("%d\n", total); // 21
return 0;
}
一次处理一行
- 你也可以只处理一行:对固定的行
r,只循环列。 - 这就是对某一行求和、或找出某行里最大值的方法。
- 把两者结合 —— 外层循环行、内层循环列 —— 就能处理整个网格。
常见错误
- 网格索引
grid[row][col]。 - 外层循环走行,内层循环走列。
现在轮到你
- 在函数任务里,网格有 3 列,所以参数是
int g[][3]。 - 不要自己写
main—— 检查器会提供。
探索
A 2-D array is a grid
Reach a cell with a[row][col] — row first, then column.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete int sum_grid(int g[][3], int rows) so it returns the total of every cell in a grid with rows rows and 3 columns. Do 不 write a main.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete int row_sum(int g[][3], int r) so it returns the total of the three cells in row r. Do 不 write a main.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
The 2×3 grid g is given. In main, print each row with the three numbers separated by single spaces, one row per line.
点击“运行”查看此处输出。