第十章 数组和指针 课后习题

10-12:编写程序,提示用户输入3个数集,每个数集包括5个double值。程序应当实现下列所有功能:
 a.把输入信息存储到一个3x5的数组中
 b.计算出每个数集(包含5个数值)的平均值
 c.计算所有数值的平均数
 d.找出这15个数中的最大值.
 e.打印出结果
 每个任务需要用一个单独的函数来实现(使用传统C处理数组的方法)。对于任务b,需要编写计算并返回一维数组平均值的函数,循环3次调用该函数来实现任务b。对于其他任务,函数应当把整个数组做为参数,并且完成任务c和d的函数应该向它的调用函数返回答案。

#include<stdio.h>

#define ROWS 3
#define COLS 5

void input_arrays(double source[][COLS],int rows); //input arrays
void average_array(double source[][COLS],double averages[],int rows); //compute the average of every arrays
void average_total(double *source,int rows); //compute average of all arrays
void output_arrays(double source[][COLS],int rows); //output arrays
double max(double source[][COLS],int rows);// find the max one

int main(void)
{
    double source[ROWS][COLS];
    double averages[ROWS];

    input_arrays(source,ROWS); //input array
    printf("the array you input is:\n");
    output_arrays(source,ROWS); //output array
    average_array(source,averages,ROWS); //compute the average value of each array
    printf("\n the average value of every array is :\n");
    for(int i = 0; i < ROWS ; i++ )
    {
        printf("%.2f ",averages[i]);
    }
    printf("\n the max one is %.2f\n",max(source,ROWS));
    return 0;
}

void input_arrays(double source[][COLS],int rows) //input arrays
{
    printf("please input 3 arrays, 5 counts for each array:\n ");
    for(int i = 0 ; i < rows ; i++)
        for(int j = 0; j < COLS ; j++)
            scanf("%lf",&source[i][j]);

}
//compute the average of every arrays
void average_array(double source[][COLS],double averages[],int rows)
{

    double subtotal = 0;

    for(int i = 0 ; i < rows; i++)
    {
        for(int j = 0 ; j < COLS; j++)
        {
            subtotal += source[i][j];
        }
        averages[i] = subtotal/COLS;
        subtotal = 0; //reset subtotal = 0
    }
}

//output arrays
void output_arrays(double source[][COLS],int rows)
{

    for(int i = 0 ; i < rows ; i++)
    {
        for(int j = 0; j < COLS ; j++)
            printf("%.2lf ",source[i][j]);
        printf("\n");
    }

}

double max(double source[][COLS],int rows)
{
    double max = source[0][0];
    for(int i = 0 ; i < rows ; i++)
    {
        for(int j = 0; j < COLS ; j++)
            if(source[i][j] > max)
                max = source[i][j];

    }
    return max;
}
posted @ 2012-10-30 15:23  maxspeed  阅读(170)  评论(0编辑  收藏  举报