6、數組 指針與字符串
6.1 數組 數組是具有一定順序關系的若干相同類型變量的集合體,組成數組的變量成為數組的元素。數組屬於構造類型。
一維數組的聲明: 類型說明符 數組名[常量表達式],若int a[10],a是整形數組,有十個元素,為a[0]……a[9]。
引用:必須先聲明后使用,只能逐個引用數組元素,而不能一次引用整個數組。每個元素相當於單個變量。
#include <iostream> using namespace std; int main() { int A[10],B[10]; int i; for(i=0;i<10;i++) { A[i]=i*2-1; B[10-i-1]=A[i]; } for(i=0;i<10;i++) { cout<<"A["<<i<<"]="<<A[i]; cout<<" B["<<i<<"]="<<B[i]<<endl; } }
數組元素在內存中順次存放,他們的地址是連續的,數組的名字是數組首元素的內存存放地址,數組名是一個常量,不能被賦值。
6.2 一維數組的初始化
可以在編譯階段使數組得到初值:
在聲明數組時對數組元素賦以初值。
例如:static int a[10]={0,1,2,3,4,5,6,7,8,9};
可以只給一部分元素賦初值。如:static int a[10]={0,1,2,3,4};
在對全部數組元素賦初值時,可以不指定數組長度。如:static int a[]={1,2,3,4,5}
例:用數組來處理求Fibonacci數列問題
#include<iostream> using namespace std; int main() { int i; static int f[20]={1,1};//初始化第0、1個數 for(i=2;i<20;i++) //求第2~19個數 f[i]=f[i-2]+f[i-1]; for(i=0;i<20;i++) //輸出,每行5個數// { if(i%5==0) cout<<endl; cout.width(12); //設置輸出寬度為12 cout<<f[i]; } }
運行結果:
1 1 2 3 5
8 13 21 34 55
89 144 233 377 610
987 1597 2584 4181 6765
應用舉例:循環從鍵盤讀入若干組選擇題答案,計算並輸出每組答案的正確率,知道輸入ctrl+z為止。每組連續輸入5個答案,a~d。
#include <iostream> using namespace std; int main() { char key[ ]={'a','c','b','a','d'}; char c; int ques=0,numques=5,numcorrect=0; cout<<"Enter the "<<numques<<" question tests:"<<endl; while(cin.get(c))//從鍵盤取值 { if(c != '\n') if(c == key[ques]) { numcorrect++; cout << " "; } else cout<<"*"; else { cout<<" Score "<<float(numcorrect)/numques*100<<"%"; ques = 0; numcorrect = 0; cout << endl; continue; } ques++; } }
運行結果:
acbba
** Score 60%
acbad
Score 100%
abbda
* ** Score 40%
bdcba
***** Score 0%