文档详情

C++数组课件-教学课件.ppt

发布:2018-05-18约1.28万字共56页下载文档
文本预览下载声明
二维数组初始化 (1)分别对各元素赋值,每一行的初始值用一对花括号括起来。例如: int a[2][3]={{1,2,3},{4,5,6}}; (2)将各初始值全部连续地写在一个花括号内,在程序编译时会按内存中排列的顺序将各初始值分别赋给数组元素。例如 int a[2][3]={1,2,3,4,5,6}; (3)只对数组的部分元素赋值。例如: int a[2][3]={1,2,3,4}; (4)可以在分行赋初值时,只对该行中一部分元素赋初值,例如: static int a[2][3]={{1,2},{1}}; 省略第一维的大小 若在定义数组时给出了全部数组元素的初值,则数组的第一维下标可以省略,但第二维下标不能省略。 下面两种定义方式等价: static int a[2][3]={1,2,3,4,5,6}; static int a[ ][3]={1,2,3,4,5,6}; static int a[2][ ]={1,2,3,4,5,6}; //错误写法 在分行定义时,也可以只对部分元素赋初值而省略第一维的下标。例如: int a[ ][4]={{1,2},{},{3,4,5}}; 等价于 int a[3][4]={{1,2,0,0},{0,0,0,0},{3,4,5,0}} ; 二维数组例 #include iostream using namespace std; int main() { float disks[2][4]; int row, col; disks[0][0] = 2.39; // Row 1, column 1 disks[0][1] = 2.75; // Row 1, column 2 disks[0][2] = 3.29; // Row 1, column 3 disks[0][3] = 3.59; // Row 1, column 4 disks[1][0] = 1.75; // Row 2, column 1 二维数组例 disks[1][1] = 2.19; // Row 2, column 2 disks[1][2] = 2.69; // Row 2, column 3 disks[1][3] = 2.95; // Row 2, column 4 // Print for (row=0; row2; row++) { for (col=0; col4; col++) { cout “$” disks[row][col] “\n”; } } return 0; } 二维数组例 #include iostream // 二维矩阵的转置 using namespace std; int main( ) { int a[2][3]={{1,2,3},{4,5,6}}; int b[3][2],i,j; cout″array a:″endl; for (i=0;i=1;i++) for (j=0;j=2;j++) b[j][i]=a[i][j]; cout″array b:″endl; for (i=0;i=2;i++) { for(j=0;j=1;j++) coutb[i][j]″ ″; coutendl; } return 0; } 二维数组例 #include iostream using namespace std; int main( ) { int i,j,row=0,colum=0,max; int a[3][4]={{5,12,23,56},{19,28,37,46},{-12,-34,6,8}}; max=a[0][0]; //使max开始时取a[0][0]的值 for (i=0;i=2;i++) //从第0行~第2行 for (j=0;j=3;j++) //从第0列~第3列 if (a[i][j]max) //如果某元素大于max { max=a[i][j]; //max将
显示全部
相似文档