为什么使用数组

  1. int a, b, c, d;
  2. int a1, a2, a3, a4, a5, a6, a7....;
  3. int a[100]; //定义100个int类型
  4. a[0], a[1], a[2], a[3], a[4]...
  5. [0][1][2][3][4][5][6][7]...
  6. //连续地址空间存储的
  7. //静态数组,大小是静态固定的,上来就要告诉计算机,我需要100个连续的int空间
  8. //然后,我想用几个就用几个。但是,千万不能要超。
  9. //a[0] ... a[99],这些是100个,但不能用a[100],这是第101个
  10. //因为,a[101]这个位置,计算机可能存储了其他的东西,有可能是危险的东西(越界访问)

一维数组

  1. #include <iostream>
  2. using namespace std;
  3. int a[10]; //全局变量,初始值默认是0
  4. int n;
  5. int main()
  6. {
  7. int b[10]; //局部变量,初始值是计算机随机给的
  8. cin >> n;
  9. for (int i = 0; i < n; i++) cin >> a[i];
  10. for (int i = 0; i < n; i++) cout << a[i] << ' ';
  11. cout << '\n';
  12. return 0;
  13. }
  1. // 逐步养成下面的代码编写风格
  2. // 学习三个月以上的,需要强制转变自己的代码风格,无需多言
  3. #include <iostream>
  4. #include <cstdio>
  5. using namespace std;
  6. const int N = 1e5 + 10;
  7. int a[N], b[N];
  8. int n;
  9. int main()
  10. {
  11. cin >> n;
  12. for (int i = 0; i < n; i++) cin >> a[i];
  13. for (int i = 0; i < n; i++) cout << a[i] << ' ';
  14. puts("");
  15. return 0;
  16. }
  1. #include <iostream>
  2. using namespace std;
  3. int main(){
  4. int n;
  5. cin >> n;
  6. int a[n];
  7. return 0;
  8. }
  1. int a[5] = {1, 2, 3, 4, 5};
  2. a[-1]; // 这是不对的,下标不能是负数
  3. memset(a, 0, sizeof a); // 把a[i]全部置成0
  4. memset(a, 0x3f, sizeof a); // 把a[i]全部置成0x3f3f3f3f

例题,2034:【例5.1】反序输出

  1. #include <iostream>
  2. #include <cstdio>
  3. using namespace std;
  4. int a[110], n;
  5. int main()
  6. {
  7. //freopen("1.in", "r", stdin);
  8. int x;
  9. while (cin >> x){
  10. a[n++] = x;
  11. }
  12. for (int i = n - 1; i >= 0; i--) printf("%d ", a[i]);
  13. puts("");
  14. return 0;
  15. }

例题,与指定数字相同的数的个数

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int a[110];
  4. int n, k;
  5. int main()
  6. {
  7. cin >> n;
  8. for (int i = 0; i < n; i++) cin >> a[i];
  9. cin >> k;
  10. int cnt = 0;
  11. for (int i = 0; i < n; i++)
  12. if (a[i] == k) cnt++;
  13. cout << cnt << endl;
  14. return 0;
  15. }

例题,年龄与疾病

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. int a, b, c, d;
  5. int main()
  6. {
  7. cin >> n;
  8. for (int i = 0; i < n; i++)
  9. {
  10. int x;
  11. cin >> x;
  12. if (x <= 18) a++;
  13. if (x >= 19 && x <= 35) b++;
  14. if (x >= 36 && x <= 60) c++;
  15. if (x >= 61) d++;
  16. }
  17. printf("%.2lf%%\n", 1.0 * a / n * 100);
  18. printf("%.2lf%%\n", 1.0 * b / n * 100);
  19. printf("%.2lf%%\n", 1.0 * c / n * 100);
  20. printf("%.2lf%%\n", 1.0 * d / n * 100);
  21. return 0;
  22. }

例题,校门外的树

  1. // 原题
  2. // 用一个数组,来表示这一段马路
  3. // 一个一个点,就可以表示是否有树的状态了

例题,【例5.3】开关门

  1. // 方法一,模拟
  2. // 方法二,数学

例题,直方图

  1. // 认真读题,看来,我们要预处理出来fmax