C Program returning an error... google doesn't know

81 Views Asked by At

The following code takes an array of integers and create an array with the mobile means (i.e. the value in i-th place is the mean of the last n elements in the array before i (if they exists); if i<n, it is the mean of the existing elements before i. Thus as an example: for n=3 1 2 3 4 5 6 -> 1 1.5 2 3 4 5

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

float *
mobMean (int x[], int n, int nval)
{
    int i, j, sum, num;
    float *means;

    if(means=malloc(sizeof(float) * nval))
    {
        for(i=0; i<nval; i++)
        {
            sum=0;
            num=0;
            for(j=i; j>=0 && i-j>=n; j--)
            {
                sum+=x[j];
                num++;
            }
            *(means+i)=(float)sum/num;
        }
    }
    else
        printf("e");
    return means;
}

int
main()
{
    int a[10], i;
    float *b;
    for(i=0; i<10; i++)
        scanf("%d", &a[i]);
    b=mobMean(a,3,10);
    for(i=0; i<10; i++)
        printf("%f", *(b+i));
    free(b);
    return 0;
}

The console (gcc compiler) returns as an output -nan 10 times consecutively. not only my pc, but also the online compiler. google doesn't have a clue of what that is. i would really appreciate your help.

1

There are 1 best solutions below

0
Vlad from Moscow On BEST ANSWER

The body of this for loop

for(j=i; j>=0 && i-j>=n; j--)

is never executed due to the condition i-j>=n because initially i - j is equal to 0.

You could write for example

        sum = x[i];
        num = 1;
        for ( j = i; j-- != 0 && num < n; ++num )
        {
            sum += x[j];
        }

Here is a demonstration program.

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

float * mobMean( const int a[], size_t size, size_t n )
{
    float *means = NULL;

    if (( means = malloc( sizeof( float ) * size ) ) != NULL)
    {
        for (size_t i = 0; i < size; i++)
        {
            float sum = a[i];
            size_t num = 1;

            for (size_t j = i; j-- != 0 && num < n; ++num)
            {
                sum += a[j];
            }

            means[i] = sum / num;
        }
    }

    return means;
}

int main( void )
{
    int a[] = { 1, 2, 3, 4, 5, 6 };
    const size_t N = sizeof( a ) / sizeof( *a );

    float *b = mobMean( a, N, 3 );
        
    if (b != NULL)
    {
        for (size_t i = 0; i < N; i++)
        {
            printf( "%.1f ", b[i] );
        }
        putchar( '\n' );
    }

    free( b );
}

The program output is

1.0 1.5 2.0 3.0 4.0 5.0

I declared local variables in for loops. You may declare them before loops in beginnings of code blocks if you marked the question with the language tag c89.