数组
数组是一个变量,由相同数据类型的一组元素组成。
变量是内存中的一块空间,数组就是内存中的一串连续的空间。
数组由标识符(数组名称),数组元素(数组中存放的数据),元素下标(数组元素的编号),元素类型(数组元素的数据类型)四个基本要素组成。
注:元素下标从0开始,数据中的每个元素都可以通过下标来访问。
c++中数组的长度是固定不变的,避免数组越界。
定义数组:
datatype arrayName[];
即:数据类型 数组名称[元素个数(可省略)];
如一维数组初始化:
int num[] = {1,3,444,566} ; 定义了一个含有4个元素的整型的名字为num的数组。
double num[6] ={}; 定义了一个含有6个元素的双精度浮点类型的名字为num的数组,元素均默认为0。
而 int num[] ={}; 则是非法的,因为无法确定该数组由多大。
附一个关于数组操作的小程序:
//求数组的最大值
int num[] = {453,3,52,88,76,9,0,999};
int numlen;
double max = num[0];
int maxIndex = 0;
int sum = 0;
double avg;
numlen= sizeof(num)/sizeof(num[0]);
for(int i=0; i<numlen; i++)
{
sum+=num[i];
}
avg=sum/numlen;
for(int i=0; i<numlen; i++)
{
cout << num[i] << "\t";//循环打印出数组中的元素
}
cout << endl;
cout << "数组有" << numlen << "个元素" << endl;
cout << "平均数为:" << avg << endl;
for(int i=0; i<numlen; i++) //依次判断,得出最大值
{
if(max < num[i] )
{
max = num[i];
maxIndex = i;//记录最大值下标
}
}
cout <<"最大值:" << max << "," << "下标:" << maxIndex << endl;
//求出奇数个数和偶数个苏
int jishu=0,oushu=0;//定义奇数和偶数奇数器
for(int i=0; i<numlen; i++)
{
if(num[i]%2 == 0)//判断是否为偶数
{
oushu++;//偶数计数器累加
}
else
{
jishu++;
}//奇数计数器累加
}
cout << "奇数个数:"<<jishu << ",偶数个数:"<< oushu << endl;
//列出可以对数组进行的操作,根据用户选择,进入相应操作,完成后提示是否继续
int choice;
char goon;
while(1)
{
cout << "1.更改某个数值。" << endl << "2.查找某个数是否在数组中。" << endl << "请选择操作:";
cin >> choice;
switch(choice)
{
case 1 :
//提示用户输入要对第几个数进行操作
int t;
cout << "请输入你想要更改第几个数组中的元素:(1-8)";
cin >> t;
cout << "请输入值:" ;
cin >> num[t-1];
cout << "更改后的数组为:" << endl;
for(int i=0; i<numlen; i++)
{
cout << num[i] << "\t";//循环打印出数组中的元素
}
cout << endl;
break;
case 2 :
//查找用户输入的数是否在数组中,是则输出该数在数组中的下标。否则输出对应结果。
int searchIndex,inputnum;
searchIndex = -1;
cout << "请输入要查找的数:" << endl;
cin >> inputnum;
for(int i=0; i<numlen; i++)
{
if(inputnum == num[i])
{
searchIndex = i;
break;
}
}
if(searchIndex == -1)
{
cout << "数组中没有这个数" <<endl;
}
else cout << "该数在数组中下标为:" << searchIndex << endl;
break;
}
cout << "是否继续:y or n";
cin >> goon;
if(goon != 'y')
{
cout << "程序结束。" << endl;
break;
}
}