C Primer Plus 编程练习10.1

题目要求: 修改程序清单10.7的rain.c程序,用指针进行计算(仍然要声明并初始化数组)

代码

/*
name:   test1.c
author: AFei
date:   2020.3.29
function:   caculate the anual rainfall, average rainfall of 5 years and average month rainfall in 5 years. You
            need use the pointer method to complete the project.
*/

#include 
#include 

#define MONTH 12
#define YEARS 5

float rainfall[YEARS][MONTH] = {
    {7.5, 8.4, 7.3, 6.4, 5.5, 5.9, 6.4, 6.3, 7.2, 10.0, 11.5, 10.7},
    {7.6, 8.2, 7.8, 5.9, 5.8, 6.1, 7.5, 7.2, 8.0, 9.5, 9.9, 10.1},
    {6.4, 4.3, 8.2, 6.3, 6.3, 7.1, 8.5, 8.2, 8.4, 7.3, 8.6, 12.6},
    {7.8, 6.2, 7.5, 7.9, 8.4, 9.3, 10.5, 7.4, 7.6, 9.8, 8.5, 8.7},
    {9.6, 7.5, 8.5, 7.4, 8.6, 8.1, 7.8, 10.5, 9.6, 10.4, 7.4, 7.6}
};

void caculate(float array[][MONTH], int years);

int main(void){
    caculate(rainfall, YEARS);
    system("pause");
    return 0;
}

void caculate(float array[][MONTH], int years){
    /*caculate the aunal rainfall*/

    int i_year = 0;
    int i_month = 0;
    float result = 0;

    float temp[5];

    float (* ptr)[MONTH];
    ptr = array;

    for(i_year; i_year < years; i_year++){
        printf("%d:  ", 2015 + i_year);
        for(i_month; i_month < MONTH; i_month++){
            result = result + *(*(ptr + i_year) + i_month);
            if(i_month == 11)   {result = result / 12;  temp[i_year] = result;}
        }
        printf("%.3f\n", result);
        i_month = 0;
        result = 0;
    }

    /*average rainfall of 5 years */

    for (i_year = 0; i_year < years; i_year++)
        result = result + temp[i_year];
    printf("the average rainfall of 5 years is %.3f\n", result / years);

    /*month average rainfall*/

    result = 0; //initialize, because result has been valued by previous program
    i_year = 0;
    i_month = 0;
    for(i_month; i_month < MONTH; i_month++){
        printf("%d:  ", 1 + i_month);
        for(i_year; i_year < YEARS; i_year++){
            result = result + *(*(ptr + i_year) + i_month);
            if(i_year == 4) result = result / 5;
        }
        printf("%.3f\n", result);
        i_year = 0;
    }

}

运行结果

2015:  7.758
2016:  7.800
2017:  7.683
2018:  8.300
2019:  8.583
the average rainfall of 5 years is 8.025
1:  7.780
2:  8.476
3:  9.555
4:  8.691
5:  8.658
6:  9.032
7:  9.946
8:  9.909
9:  10.142
10:  11.428
11:  11.466
12:  12.233
请按任意键继续. . .

如果本篇博文解决了你的问题,请帮忙点个赞
如果有问题可以加博主QQ:2240172425,一起交流学习经验。

你可能感兴趣的:(C Primer Plus 编程练习10.1)