『C/C++』Eg4: Find the average of elements of a custom type

This question requires the implementation of a function to find the average value of Na collection element S[], where the type of the collection element is custom ElementType.

Function interface definition:

ElementType Average( ElementType S[], int N );

The given collection elements are stored in the array S[], and the positive integer Nis the number of array elements. The function must return Nthe S[]average of elements, and its value must also be ElementTypeof type.

Sample referee test procedure:

#include <stdio.h>

#define MAXN 10
typedef float ElementType;

ElementType Average( ElementType S[], int N );

int main ()
{
    
    
    ElementType S[MAXN];
    int N, i;

    scanf("%d", &N);
    for ( i=0; i<N; i++ )
        scanf("%f", &S[i]);
    printf("%.2f\n", Average(S, N));

    return 0;
}

/* 你的代码将被嵌在这里 */

Input sample:

3
12.3 34 -5

Sample output:

13.77

answer:

ElementType Average( ElementType S[], int N )
{
    
    
    int i;
    double sum,ave;
    for(i=0;i<N;i++)
        sum+=S[i];
    ave=sum/N;
    return ave;
}

Guess you like

Origin blog.csdn.net/hsjsiwkwm/article/details/130926072