在 C++ 中,数组是一种存储固定大小的相同类型元素的序列。数组的所有元素都存储在连续的内存位置上。这种数据结构非常适合于存储具有固定数量和相同数据类型的元素集合。
一、声明数组
声明的基本语法如下:
数据类型 数组名[数组大小];
例如,声明一个类型为 int
的数组,包含 10 个元素:
int myArray[10];
二、初始化数组
int myArray[5] = {10, 20, 30, 40, 50};
三、访问数组元素
int value = myArray[2]; // 访问第三个元素
示例代码
#include <iostream>
using namespace std;
int main() {
int myArray[5] = {10, 20, 30, 40, 50};
// 输出所有数组元素的值
for(int i = 0; i < 5; ++i) {
cout << "Element at index " << i << ": " << myArray[i] << endl;
}
return 0;
}
注意
•数组的大小必须在编译时已知,且不能更改。
•数组索引越界是常见的错误,可能会导致未定义的行为。
•对于更复杂的用例,您可能需要使用 C++ 的标准模板库(STL)中的容器,如 std::vector,它提供了可以动态改变大小的数组。
•数组的元素存储在连续的内存位置上,这使得访问数组元素非常快。
四、示例代码
- 计算器支持加减乘除
#include <iostream>
using namespace std;
int add(int a,int b)
{
return a+b;
}
int min(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
float divRet(int a,int b)
{
return (float)a/b;
}
int main() {
int a;
int b;
char calWay;
while(1){
cout << "请输入两个数:"<< endl;
cin >> a;
cin >> b;
cout<<"请输入运算符号:+ - * /" <<endl;
cin >> calWay;
switch(calWay){
case '+':
printf("两数之和是%d\n",add(a,b));
break;
case '-':
printf("两数之差是%d\n",min(a,b));
break;
case '*':
printf("两数之积是%d\n",mul(a,b));
break;
case '/':
printf("两数之余是%f\n",divRet(a,b));
break;
default:
printf("运算符输入错误,请重新输入\n");
}
}
}