主要内容 #
1. 如何读取数组的长度 #
假设有一个很长的数组,如何获得它的长度呢?
int a [] = { 1,4,5,9,15,125,12,12,1,12,14,15,48,787,7,9,9,954,65,32,21, 45,2,9,15,12,1255,12,12,182,9,15,12,125,58,42,9,15,5,12,12,15,12,12, 15,12,12,15,12,12,15,12,12,15,12,12,15,12,12,15,12,12,15,12,12,15,12, 12,15,12,12,15,12,12,15,12,12,15,12,12,112,1215,12,12,1,2,9,15,12,1585, 12,12,12,9,152,14,155,12,12,1582,9,15,48,78,0,7,8,9,15,12,9,2,12,9,15, 12,122,125,12,12,1,9,15,12,124,15,48,72,9,15,12,1282,9,15,12,125,12,12,15,12};
换一个问题,小王花了 10 块钱买包子,每个包子 2 元钱,请问他买了几个包子?
类似的,假如我们知道了数组的总大小,也知道数组中一个元素的大小,那么就可以计算出数组中的元素数量了。
在字符串一节中,我们讲解过字符串长度的求法。数组的长度也类似,只不过,数据的末尾没有自动添加的’/0′
请试一试,输出上面数组 a 的大小。
/* 请完成后,查看示例程序 */
请看代码
#include < iostream > using namespace std; int main() { int a [] = { 1,4,5,9,15,125,12,12,1,12,14,15,48,787,7,9,9,954,65,32,21, 45,2,9,15,12,1255,12,12,182,9,15,12,125,58,42,9,15,5,12,12,15,12,12, 15,12,12,15,12,12,15,12,12,15,12,12,15,12,12,15,12,12,15,12,12,15,12, 12,15,12,12,15,12,12,15,12,12,15,12,12,112,1215,12,12,1,2,9,15,12,1585, 12,12,12,9,152,14,155,12,12,1582,9,15,48,78,0,7,8,9,15,12,9,2,12,9,15, 12,122,125,12,12,1,9,15,12,124,15,48,72,9,15,12,1282,9,15,12,125,12,12,15,12}; int size = sizeof(a) / sizeof(int); // 注意,sizeof(int) 可以替换为 sizeof(a[0]) cout << "size = " << size << endl; return 0; }
2. 遍历数组元素 #
这是一种重要的程序结构,请掌握。
请试一试,使用 while 和 for 遍历下面数组。
int dashima [] = { 1,4,5,9,15,125,12,12,1,12,14,15,48,78,12,12,15,12}; /* 请完成后,查看示例程序 */
请看代码
#include < iostream > using namespace std; int main() { int dashima [] = { 1,4,5,9,15,125,12,12,1,12,14,15,48,78,12,12,15,12}; int size = sizeof(a) / sizeof(int); // while int i(0); cout << "Using while: " << endl; while (i < size) cout << dashima[i++]; cout << endl << endl; // for 1 cout << "Using for 1: " << endl; for (int j = 0; j < size; j++) cout << dashima[j]; cout << endl << endl; // for 2 cout << "Using for 2: " << endl; for (int j = 0; j < size; ) cout << dashima[j++]; cout << endl << endl; return 0; }