Chinaunix首页 | 论坛 | 博客
  • 博客访问: 41886
  • 博文数量: 11
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 126
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-11 23:27
文章分类

全部博文(11)

文章存档

2014年(2)

2013年(9)

我的朋友

分类: C/C++

2013-11-29 23:00:51

数组


数组    可以用一个名称进行访问的一组数据类型相同的变量。

声明数组的通常格式为:
    dateType arrayName[ size ];
数组变量    C++的一种变量,它包含一些类型相同而且可以用同一个变量名进行访问的元素。
元素    数组中的成员。
数组索引    表示数组中某一具体元素的整数值。


一维数组    存储一列数据的数组。

以null结尾的字符串或C字符串    在数据最后含有一个null字符的字符数组(C字符串)。
例如    char name[25]; 是一个含有25个字符的数组,就是一个以null结尾的字符串,该name可以容纳24个字符,它的第25个字符必须是null(ASCII码中的零),这类字符串称为C字符串,在C++的string类被提出之前,通常用它来在程序中实现对文本数据的处理。即使如今我们也会经常在C/C++程序中看到它们。

零索引    数组第一个元素的索引值为0。

注意一点:当需要对数组进行遍历时,应当首先考虑使用for循环。
下面是一个电话账单的程序:

点击(此处)折叠或打开

  1. //计算一年来电话账单平均值的程序

  2. #include<iostream>
  3. using namespace std;

  4. int main()
  5. {
  6.     //声明一个大小为12的float型数组
  7.     float phone_bills[12];
  8.     float sum, ave;

  9.     int i;    //i是循环变量

  10.     cout << "\n A program that determines yearly total and average monthly phone bill.\n";

  11.     //获取每月账单信息
  12.     for(i = 0; i< 12; ++i)
  13.     {
  14.         cout <<"Enter bill for month #" << i+1 <<" $";
  15.         cin >> phone_bills[i];
  16.     }

  17.     //下面计算平均值
  18.     sum = 0.0;
  19.     for(i = 0; i < 12; ++i)
  20.     {
  21.         sum = sum + phone_bills[i];
  22.     }

  23.     ave = sum/12;
  24.     cout.precision(2);
  25.     cout.setf(ios::fixed);
  26.     cout << "Total yearly phone cost is $" << sum <<endl;
  27.     cout << "Average monthly phone bill is $" << ave <<endl;

  28.     return 0;
  29. }
运行结果如下:
        点击(此处)折叠或打开
  1. A program that determines yearly total and average monthly phone bill.
  2. Enter bill for month #1 $33.66
  3. Enter bill for month #2 $33.66
  4. Enter bill for month #3 $33.66
  5. Enter bill for month #4 $33.66
  6. Enter bill for month #5 $33.66
  7. Enter bill for month #6 $33.66
  8. Enter bill for month #7 $33.66
  9. Enter bill for month #8 $33.66
  10. Enter bill for month #9 $33.66
  11. Enter bill for month #10 $33.66
  12. Enter bill for month #11 $33.66
  13. Enter bill for month #12 $33.66
  14. Total yearly phone cost is $403.92
  15. Average monthly phone bill is $33.66
  16. 请按任意键继续. . .


C++不会自动为数组进行初始化,我们可以手动的在声明数组时对它进行初始化;在声明时对一维数组进行初始化的一般格式如下:
    dateType arrayName[size] = { list of array values };
其中list of array values 就是对数组进行初始化所使用的所有的数值列表,值与值之间要用逗号分开。列表中的第一个数据被赋值给数组的第一个元素(索引为0的元素),依次类推。注意这些值不是固定的,如果需要的话可以在程序中对它进行修改


数组越界    试图访问不是合法声明的数组元素。




















阅读(1339) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~