Search code examples
carraysfloating-pointmedian

Median calculation from float array in C


I have a program which reads floating point numbers from a .txt file and puts them into an array but I have a problem with calculating median. Everything is working perfectly except from this. What am I doing wrong?

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


int compare (const void * a, const void * b)
{
  float fa = *(float*) a;
  float fb = *(float*) b;
  return (fa > fb) - (fa < fb);
}



//median calculations//
float median1(float[],int); 
float median1(float array[],int n) 
{  
qsort(array, n, sizeof(float), compare);

if(n%2==0)  
    return (array[n/2]+array[n/2-1])/2;  
else  
    return array[n/2];  
}



float x,l=~(257<<23),a,s,t,median;
main(int n,char**f)

{
char fname[20];
int i;
a=-l;

printf("Please type the file name with an extension (.txt)\n");
scanf("%s", fname);


f=fopen(fname,"r");
for(n=0;fscanf(f,"%f",&x)>0;n++,s+=x,x<l?l=x:0,x>a?a=x:0,t+=x*x);

float array[n];

fseek (f, 0, SEEK_SET);

for (i=0; i<n; i++) 
        {
            fscanf (f, "%f", &(array[n]));
        }

median=median1(array,n);  

printf("Sample size = %d\n", n);
printf("Minimum = %f\n", l);
printf("Maximum = %f\n", a);
printf("Mean = %f\n", s/n);
printf("Median = %f\n",median);
printf("Standard deviation = %f\n", sqrtf(t/n));

return 0;
} 

Solution

  • fscanf (f, "%f", &(array[n]));
    

    should be

    fscanf (f, "%f", &(array[i]));
    

    You are only writing to one array element and that one is out-of-bound.

    Even if this wouldn't result in undefined behavior, you would still work with garbage values later on.

    See @JonathanLeffler's comment for some further remarks on your code.