开发者

Find element in array with lowest difference from average in C

开发者 https://www.devze.com 2023-01-24 00:27 出处:网络
I need to set the size of array. After that I start to input numbers to dill this array. During that procedure I count sum for calculating average later.

I need to set the size of array. After that I start to input numbers to dill this array. During that procedure I count sum for calculating average later.

Now I have an array and average and I need to find the element with lowest difference from average.

Like:

array size = 3

input = 1

input = 2

input = 3

average = 2

Counting

abs( 1 - 2 ) = 1

abs( 2 - 2 ) = 0

abs( 3 - 2 ) = 1

So the lowest difference have the element with v开发者_如何转开发alue 2. And in the end of the program I need to out put that element from array and its index.

So far I came up with:

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char **argv )
{

    int n = 0, i = 0;

    double average = 0;
    int sum = 0;
    double tmp = 0;

    double min = 0;
    int index = 0;

    int *a;
    double *b;

    printf("Amount of elements = ");
    scanf("%d", &n);

    if( 0 == n )
    {
        return 0;
    }

    if( n < 1 || n > 10 )
    {
        return 0;
    }

    a = ( int* )malloc( sizeof( *a ) * n );
    b = ( double* )malloc( sizeof( *b ) * n );

    while( i < n )
    {
        printf("Input number: ");
        scanf("%d", &a[i]);
        sum += a[i];
        i++;
    }

    average = ( double )( sum / n );

    printf("Average = %.3lf\n", average);

    for( i = 0; i < n; i++ )
    {
        tmp = abs( ( double )( a[ i ] ) - average );
        b[ i ] = tmp;
    }

    /* for( i = 0; i < n; i++ )
    {

    } */

    free( a );
    free( b );

    return 0;

}

Update: My apologies. The question is how to achive the last part without macking this simple program even more complicated.

Thank you all for help.


You need to use the 2 variables defined to hold the lowest difference and index of the lowest difference in something like

    min = b[0]; /* initialize min with b[0] */
    index = 0;  /* and index with 0 */
    for( i = 1; i < n; i++ ) /* loop from 1 onwards ... index 0 was used for initialization */
    {

        /* maybe change min to b[i] */
        /* and index to i */

    }

    free(a);
    free(b);
0

精彩评论

暂无评论...
验证码 换一张
取 消