0
点赞
收藏
分享

微信扫一扫

C语言:二维数组及所占用的字节

今天你读书了吗 2022-04-13 阅读 111
c语言

以数组作为数组的元素“数组中的数组”即二维数组。

语法如下:

类型 数组标识[一维数组长度][二维数组长度] 如:float rain[5][12]

二维数组占用的字节数计算方法为:二维数组单个元素所占的字节 * 元素个数。上面声明的rain[5][12],共5*12=60个元素,float类型占用4个字节,因此为 4*60=240个字节。

下面的代码片段有两个实例,一个计算5年的总降水量、5年中月平均降水量:

#include <stdio.h>
/*
时间:2022-04-10 19:55
作者:sgbl888
功能:学习二维数组(计算5年总降水量、每月平均降水量)
*/
#define YEARS 5 //5年
#define MONTHS 12 //每年12个月
//定义一个二维数组(数据一共5行表示5年,每行12列表示12个月)
const float rain[5][12] = {
    {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 main(){
    int year, month;
    float subtot, total;
    //计算5年来每个月的总降水量
    printf("年份         降水量\n");
    for(year = 0, total = 0; year < YEARS; year++){ //遍历每一年。
        for(month = 0, subtot = 0; month < MONTHS; month++){ //遍历每年的12个月,每当外层循环1次,内层循环12次
            subtot += rain[year][month];
        }
        printf("%d %12.1f\n", 2015 + year, subtot);
        total += subtot; //把每年12个月的降累加到total上
    }
    printf("年平均降水量为 %.1f\n", total / year);
    printf("------------------------\n");

    //计算5年来每个月的平均降水量
    printf("  一 月\t  二 月\t  三 月\t  四 月\t  五 月\t  六 月\t  七 月\t  八 月\t  九 月\t  十 月\t十一月\t十二月\n");
    for(month = 0; month < MONTHS; month++){ //遍历每个月
        for(year = 0, subtot = 0; year < YEARS; year++){ //遍历每年
            subtot += rain[year][month];
        }
        printf("%5.1f\t", subtot / YEARS);
    }
    printf("\n------------------------\n");

    //测量二维数组rain占用多少字节
    printf("rain[5][12] use %zd Byte\n", sizeof rain); //float占用4个字节,共有60个元素,因此占用240个字节

    return 0;
}

 

 

举报

相关推荐

0 条评论