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%