C语言之数组篇

xiaoxiao2021-02-28  113

数组(array)由一系列类型相同的元素构成。数组声明(array declaration)中包括数组元素的数目和元素的类型。编译器根据这些信息创建合适的数组。

float candy[365];      /* array of 365 floats */

char code[12];          /* array of 12 chars   */ int states[50];           /* array of 50 ints    */

  方括号([])表示数组,方括号内的数字指明了数组所包含的元素数目。要访问数组中的元素,可以使用下标(索引)来表示单个元素,下标从0开始计数。

数组的初始化如下: int powers[8] = {1,2,4,6,8,16,32,64};     使用花括号括起来的一系列数值来初始化数组。数值之间用逗号分隔,数值和逗号之间可以使用空格符。上例中,power[0]赋值为1,power[1]赋值为2,依次类推。     与普通变量相似,在初始化之前,数组元素的数值是不确定的。     当数值数目少于数组元素数目时,多余的数组元素被初始化为0。     数组的大小 = sizeof(数组名)/sizeof(数组元素的类型)     有时需要使用只读数组,也就是程序从数组中读取数值,但是程序不向数组中写数据。这时,可以使用关键字const: const int days[MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31};

二维数组的声明如下: float rain[5][12];     理解这种声明的一种方法是首先查看位于中间的部分: float rain[5][12];  // rain is an array of 5 somethings     蓝色部分说明rain是一个包含5个元素的数组。 float rain[5][12];  // an array of 12 floats     蓝色部分说明每个元素的类型是float[12]。     综上,rain具有5个元素,并且每个元素都是包含12个float数值的数组。按此推理,rain[0]是一个包含12个float数值的数组,该数组的首元素是rain[0][0],第二个元素是rain[0][1],依此类推。 

**  * 功能:计算年降水总量、平均量、月降水平均量  * 目的:二维数组的使用  */ #include <stdio.h> #define MONTHS 12    // number of months in a year #define YEARS   5    // number of years of data int main(void) { // initializing rainfall data for 2000 - 2004 const float rain[YEARS][MONTHS] = { {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6}, {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3}, {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4}, {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2}, {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2} }; int year, month; float subtot, total; printf(" YEAR    RAINFALL  (inches)\n"); for (year = 0, total = 0; year < YEARS; year++) {             // for each year, sum rainfall for each month    for (month = 0, subtot = 0; month < MONTHS; month++) { subtot += rain[year][month]; } printf("] .1f\n", 2000 + year, subtot); total += subtot; // total for all years  } printf("\nThe yearly average is %.1f inches.\n\n", total/YEARS); printf("MONTHLY AVERAGES:\n\n"); printf(" Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct "); printf(" Nov  Dec\n"); for (month = 0; month < MONTHS; month++) {             // for each month, sum rainfall over years    for (year = 0, subtot =0; year < YEARS; year++) { subtot += rain[year][month]; }    printf("%4.1f ", subtot/YEARS); } printf("\n"); return 0; }

转载请注明原文地址: https://www.6miu.com/read-71305.html

最新回复(0)