定义:
#include<iostream>
using namespace std;
int main()
{
//数组定义
int A[5]; //单定义数组长度
int B[5] = { 1,2,3 ,6,7 }; //定义数组长度和内容
int C[] = { 1,2,3,4,7 }; // 直接以类型确定长度
//数组元素下标从0开始索引
A[0] = 54;
A[1] = 12; //直接赋值
A[2] = 45;
A[3] = 89;
A[4] = 21;
cout << A[0] << endl;
cout << A[1] << endl;
cout << A[2] << endl;
cout << A[3] << endl;
cout << A[4] << endl;
for (int i = 0; i <= 4; i++)
{
cout << B[i] << endl;
cout << C[i] << endl;
}
system("pause");
return 0;
}
一维数组:
#include<iostream>
using namespace std;
int main()
{
//一维数组
int A[] = { 1,3,1,4,8,9 };
cout << sizeof(A) << endl; //sizeof 获取数组占用内存大小
cout << sizeof(A[0]) << endl; // 单个元素占用内存大小
cout << "数组的长度为" << sizeof(A) / sizeof(A[0]) << endl; //从而计算数组长度
// 获取数组首地址
// 学过汇编会更好理解
cout << "数组首地址为" << A << endl; // 即不同于MATLAB,输出的为地址,不是数组的所有内容
cout << "元素首地址" << &A[1] << endl; // 注意&
// 默认16进制
// 十进制如下
cout << "数组首地址为" << (int)A << endl;
cout << "元素首地址" << (int)&A[1] << endl;
system("pause");
return 0;
}
练习1:
#include<iostream>
using namespace std;
int main()
{
//在一个数组中记录了五只小猪的体重,如:intarr[5] = { 300,350,200,400,250 };
//找出并打印最重的小猪体重。
int arr[5] = { 300,350,200,400,250 };
int maxmium = arr[0]; //初始化最大值
for (int i = 1; i < 5; i++)
{
if (maxmium <= arr[i])
{
maxmium = arr[i];
}
}
cout << "最重的小猪体重为" << maxmium << endl;
system("pause");
return 0;
}
练习2:
#include<iostream>
using namespace std;
int main()
{
//案例描述:请声明一个5个元素的数组,并且将元素逆置
//(如原数组元素为:1, 3,2, 5,4;逆置后输出结果为:4, 5,2, 3,1);
int A[] = { 5,9,4,3,8,1,2 }; //这里测试代码效果,可随意更改。
int temp; //中间变量
int length; //数组长度
//cout << size(A) << endl; //size 直接获取长度?
length = size(A);
if (length % 2 == 1) //如果为奇数
{
for (int i = 0; i < (length + 1) / 2; i++)
{
temp = A[i];
A[i] = A[length - 1 - i];
A[length - 1 - i] = temp;
}
}
else //如果为偶数
{
for (int i = 0; i < length / 2; i++)
{
temp = A[i];
A[i] = A[length - 1 - i];
A[length - 1 - i] = temp;
}
}
cout << "逆置后数组为:" << endl;
for (int i = 0; i < length; i++)
{
cout << A[i] << " ";
}
system("pause");
return 0;
}
其中牵扯到的数学关系请自行演算。