Function with vectors in C

Asked

Viewed 1,168 times

0

I would like to know what a function in C would look like if it received a vector with N elements and returned the amount of elements that are above the arithmetic mean of the vector itself.

1 answer

2

Here is an (tested) example of how to calculate the quantidade de elementos contained in a vector that are acima da média aritmética of that same vector.

For greater readability, clarity and modularity of the code, I divided the task into two functions: one of them double media( double vetor[], int tam ) calculates the arithmetic mean of the elements in one vector, while the other int media_qtd_acima( double vetor[], int tam ) counts how many elements are above average:

#include <stdio.h>

double media( double vetor[], int tam )
{
    int i = 0;
    double soma = 0.0;

    for( i = 0; i < tam; i++ )
        soma += vetor[ i ];

    return soma / tam;
}

int media_qtd_acima( double vetor[], int tam )
{
    int i = 0;
    int n = 0;
    double med = media( vetor, tam );

    for( i = 0; i < tam; i++ )
        if( vetor[i] > med )
            n++;

    return n;
}

int main( void )
{
    double v[ 10 ] = { 5.03, 5.7, 2.89, 1.97, 1.04, 3.3, 7.8, 9.12, 0.08, 8.41 };

    printf( "Media: %g\n", media( v, 10 ) );
    printf( "Qtd. de amostras acima da media: %d\n", media_qtd_acima( v, 10 ) );

    return 0;
}

Exit:

./media 
Media: 4.534
Qtd. de amostras acima da media: 5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.