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;
}
x,l, etc? Make them local. I'm puzzled about the initializer forl— quite honestly, I've no idea what it's supposed to do with bit operations on an integer assigned to afloat. You'd also lose any marks I was giving out for the linefor(n=0;fscanf(f,"%f",&x)>0;n++,s+=x,x<l?l=x:0,x>a?a=x:0,t+=x*x);. That is diabolical — ridiculous — code.