標籤:
數組(array)是一種資料格式,能夠儲存多個同類型的值。
下面貼出代碼:
#include<iostream>
int main()
{
using namespace std;
int yams[3];
yams[0] = 7;
yams[1] = 8;
yams[2] = 6;
int yamcosts[3] = {20,30,50};
//yamcosts[3] = {20,30,50}; //not allowed;
//yams = yamcosts; //not allowed;
float fa[5] = {0.5f,2.3f} ; //只初始化一部分元素,則編譯器將其他元素置為0
float fb[5] = {0.0}; //將所有元素都置為0
cout<<yams[0]<<" "<<yams[1]<<" "<<yams[2]<<endl;
cout<<yamcosts[0]<<" "<<yamcosts[1]<<" "<<yamcosts[2]<<endl;
cout<<sizeof yams<<endl;
cout<<sizeof yams[0]<<endl;
cout<<fa[3]<<endl;
short test[] = {2,5,97,4};
int num_elements = sizeof test/sizeof (short);//當不關心數組元素個數時,這是一種很好的解決方案。
cout<<num_elements<<endl;
return 0;
}
擴充:
1、數組之所以被稱為複合類型,是因為他是使用其他類型來建立的。不能僅僅將某種東西聲明為數組,它必須是特定類型的數組。類如:flaot loans[20],其中loans的類型是float數組而不是數組。
2、有效下標的重要性。編譯器不會檢查下標是否有效。例如,如果將一個值賦給不存在的元素months[101],編譯器並不會報錯。但這種賦值可能破壞資料,也可能導致程式異常終止。所以必須確保程式使用有效下標值。
C++數組