C++ 数组的全面解析与应用
1. 一维数组的基本操作
在 C++ 中,数组是一种非常重要的数据结构。我们先来看一个计算数组元素平均值的例子:
double total = 0;
for(j=0; j<SIZE; j++) //read figures from array
total += sales[j]; //to find total
double average = total / SIZE; // find average
cout << "Average = " << average << endl;
return 0;
这里使用了一个 const
变量 SIZE
来定义数组的大小和循环的限制:
const int SIZE = 6;
使用变量而不是具体的数字,使得修改数组大小变得更加容易,只需要修改一行代码即可。
2. 数组的初始化
数组在定义时可以直接为每个元素赋值。例如,下面的程序 days.cpp
用于计算从年初到用户指定日期的天数:
// days.cpp
// shows days from start of year to date specified
#include