C-多维数组
时间:2020-02-23 14:31:58 来源:igfitidea点击:
在本教程中,我们将学习C编程语言中的多维数组。
在先前的教程中,我们已经介绍了一维数组和二维数组。
在C语言中,我们可以像1D和2D数组一样创建多维数组。
多维数组的语法如下。
type arrName[size1][size2]...[sizeN];
在上面的语法类型中,可以是任何有效的类型,例如int,float等。
arrName是数组的名称,而 [size1],[size2],...是数组的尺寸。
数组维数限制由用于编译C程序的编译器确定。
3维数组
在下面的示例中,我们将创建一个名为" scoreboard"的3D数组,类型为" int",以连续2年保持2位玩家的3场比赛得分。
//scoreboard[player][match][year] int scoreboard[2][3][2];
该数组将如下所示。
让我们用C编写一个程序,在2年的3场比赛中得到2名球员的得分。
/** * file: 3d-array.c * date: 2010-12-25 * description: 3d array program */ #include <stdio.h> int main(void) { //variable int scoreboard[2][3][2], player, match, year; //user input printf("---------- INPUT ----------\n\n"); for (year = 0; year < 2; year++) { printf("---------- Year #%d ----------\n", (year + 1)); for (player = 0; player < 2; player++) { printf("Enter score of Player #%d\n", (player + 1)); for (match = 0; match < 3; match++) { printf("Match #%d: ", (match + 1)); scanf("%d", &scoreboard[player][match][year]); } } } //output printf("\n\n---------- OUTPUT ----------\n\n"); for (year = 0; year < 2; year++) { printf("---------- Scoreboard of Year #%d ----------\n", (year + 1)); for (player = 0; player < 2; player++) { printf("----- Player #%d -----\n", (player + 1)); for (match = 0; match < 3; match++) { printf("Match #%d: %d\n", (match + 1), scoreboard[player][match][year]); } } } printf("End of code\n"); return 0; }
---------- INPUT --------- ---------- Year #1 --------- Enter score of Player #1 Match #1: 80 Match #2: 40 Match #3: 70 Enter score of Player #2 Match #1: 50 Match #2: 90 Match #3: 30 ---------- Year #2 --------- Enter score of Player #1 Match #1: 80 Match #2: 90 Match #3: 70 Enter score of Player #2 Match #1: 40 Match #2: 60 Match #3: 70 ---------- OUTPUT --------- ---------- Scoreboard of Year #1 --------- ----- Player #1 ---- Match #1: 80 Match #2: 40 Match #3: 70 ----- Player #2 ---- Match #1: 50 Match #2: 90 Match #3: 30 ---------- Scoreboard of Year #2 --------- ----- Player #1 ---- Match #1: 80 Match #2: 90 Match #3: 70 ----- Player #2 ---- Match #1: 40 Match #2: 60 Match #3: 70 End of code