數組

假設現在要做一個班級的管理系統,存學生的語文分數,假設班裏有56個人,怎麼存?

寫代碼的:1.可讀性和可維護性較強 2.可拓展性較強 3.健壯性較強


數組:可以存儲多個同類型的值,上面的例子可以就可以用數組來存  

1. 存儲在每個元素中的類型

2. 數組名字

3. 數組中的元素個數


typename arrayname[arraySize]

arraySize: 有要求要是常數,必須要是常量


【0】【1】【2】【3】【4】【5】【6】

一般是通過角標來操作數組裏面的值,需要知道第一個角標為0

#include<iostream>
using namespace std;

int main() {
    // C++ 裏面只定義但不給初始化變量(賦值)的情況下,裏面的數據是不固定的
    int yams[3];
    yams[0] = 7;
    //yams[1] = 8;
    yams[2] = 6;

    // 定義的同時賦值
    int yamcosts[3] = {20, 30, 5};
    cout << yams[0] << ", " << yams[1] << ", " << yamcosts[1] << endl;
    return 0;
}
xaye@orange:~/code/dev/9$ ./a.out 
7, 29280, 30

#include<iostream>
using namespace std;

int main() {
    // C++ 裏面只定義但不給初始化變量(賦值)的情況下,裏面的數據是不固定的
    int yams[3];
    yams[0] = 7;
    yams[1] = 8;
    yams[2] = 6;

    // 定義的同時賦值
    int yamcosts[3] = {20, 30, 5};
    cout << "Total yams = " << yams[0] + yams[1] + yams[2] << endl;
    cout << "The package with " << yams[1] << "yams costs " << yamcosts[1] << " cenrs per yam.";
    int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1] + yams[2] * yamcosts[2];
    cout << "The total yam expense is " << total << " cents." << endl;

    cout << "Size of yams array = " << sizeof yams << " bytes." << endl;
    cout << "Size of one element = " << sizeof yams[0] << " bytes." << endl;
    return 0;
}
xaye@orange:~/code/dev/9$ ./a.out 
Total yams = 21
The package with 8yams costs 30 cenrs per yam.The total yam expense is 410 cents.
Size of yams array = 12 bytes.
Size of one element = 4 bytes.

注意事項

  1. C++中變量 未賦值的情況下,默認值是不確定的
  2. 角標不要越界,數組越界不報錯但會導致程序異常,一般有內存訪問出錯的閃退
  3. 快速將數組每個默認值設置為 0 :int number[9] = {0};