我有一个程序从.txt文件中读取浮点数并将它们放入数组中,但我在计算中位数时遇到问题。除此之外,一切都很完美。我做错了什么?
#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;
}
答案 0 :(得分:4)
fscanf (f, "%f", &(array[n]));
应该是
fscanf (f, "%f", &(array[i]));
您只是写入一个数组元素,而且那个数组元素超出范围。
即使这不会导致未定义的行为,您仍然可以使用垃圾值。
请参阅@ JonathanLeffler对您的代码的进一步评论的评论。
答案 1 :(得分:1)
它干净利落地编写:
gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
-Wold-style-definition -Werror med.c -o med
这表明你并不是太可怕了。我没有修复l
的初始值设定项。在您开始在其中累积值之前,我确实将s
和t
都归零。代码不会检查fscanf()
是否适用于第二遍。我没有修复它来从标准输入读取或从其参数中获取文件名,其中任何一个都可以使它更加可用。
给定输入数据:
1.2
3.5
2.9
4.6
它产生输出:
Sample size = 4
Minimum = 1.200000
Maximum = 4.600000
Mean = 3.050000
Median = 3.200000
Standard deviation = 3.288617
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int compare(const void *a, const void *b);
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];
}
int main(void)
{
float x;
float l = ~(257 << 23);
float a;
float s = 0.0;
float t = 0.0;
float median;
int n;
FILE *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");
if (f == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", fname);
return 1;
}
for (n = 0; fscanf(f, "%f", &x) > 0; n++)
{
s += x;
if (x<l) l = x;
if (x>a) a = x;
t += x * x;
}
float array[n];
fseek(f, 0, SEEK_SET);
for (i = 0; i < n; i++)
{
fscanf(f, "%f", &(array[i]));
}
fclose(f);
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;
}