Try   HackMD
tags: tgirc早修book

一維陣列

當遇到需要宣告同類型的多個變數時,如果一個個宣告變數會很麻煩,因此可以使用陣列(array)這個資料型態,來存取多個變數

基本結構

以多個變數儲存

宣告三個變數來存放各個值,占空間又不方便操作

int score0=90; int score1=77; int score2=85;

宣告陣列

宣告一個長度為 3 ,名稱叫做 score 的陣列,該陣列存有 3 個型態為 int 的變數

int score[3]; score[0]=90; score[1]=77; score[2]=85;

輸入各元素的值

輸入時可以用迴圈來簡化流程

#include <iostream> using namespace std; int main(){ for(int i=0;i<3;i++){ //依陣列大小進行 3 次輸入 cin>>score[i]; } return 0; }

宣告陣列時, [] 中的數字表示陣列的長度,且陣列的編號是從零開始,編號皆為正整數。
陣列中每個元素的型別,皆等於宣告的型別。

編號 數值
0 90
1 77
2 85

陣列的更多細節

解題時,建議將陣列宣告在 main 函數區塊的外部,以避免 Stack Overflow 的風險

#include <iostream> using namespace std; int score[3]; //這裡 int main(){ for(int i=0;i<3;i++){ cin>>score[i]; } for(int i=0;i<3;i++){ cout<<"score["<<i<<"]= "<<score[i]<<'\n'; } return 0; }

這樣宣告會讓 score 陣列成為一個 全域變數,因為若是宣告過大的陣列在 main() (包含其他函數)裡面,可能會導致程式當掉,宣告在全域變數就能避免這個問題。

陣列一宣告完後大小就會固定不能改變,因此在宣告長度時要考慮到最糟糕的情況所需要的數量,並留至少 5~10 作為緩衝,降低溢位風險,題目如果沒有講明最大範圍的話都可以多宣告一些

陣列的初始值

int ary[3]={0,1,0};

{ } 僅限用於初始化,並不能用於對已宣告好的陣列做賦值(assign)的動作

以下為錯誤示範,會導致編譯錯誤

int ary[3]; ary[3]={0,1,0}

初始化時沒有被指定到的部分會被自動填入 0,可以看下方的例子

#include <iostream> using namespace std; int ary[3]={0}; int main(){ for(int i=0;i<3;i++){ cout<<ary[i]<<' '; } return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這段程式碼並不是將每一格都變成 0,而是第一位初始化成 0 後再補上 0

所以下方的程式碼並不會因為第一位是 1,所以其他格都變為 1

#include <iostream> using namespace std; int ary[3]={1}; int main(){ for(int i=0;i<3;i++){ cout<<ary[i]<<' '; } return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →