我制作了这个程序来订购数据集并显示最大值,最小值,平均值和中值。最初我把所有东西都放在了主要部分,我决定通过制作功能来清理它。平均功能是工作基金,但在增加了几个平均值后返回的值为&nan;有什么建议?在此先感谢你们
#include <stdio.h>
int findSize();
double findAverage(int size, double num[]);
double findMedian(int size, double num[]);
void findLowtoHigh(int size, double num[]);
void findHightoLow(int size, double num[]);
int main()
{
while(1)
{
int size = findSize();
if(size <= 1)
{
return 0;
}
double num[size];
double holder;
double lowest;
double highest;
double average;
double median;
fprintf(stdout, "\n");
for(int i = 0; i <= size - 1; i++)
{
int j = i+1;
fprintf(stdout, "Please enter number %d: ", j);
fscanf(stdin, "%lf", &num[i]);
}
if(size > 1)
{
for(int y = 0; y < size - 1; y++)
{
for(int k = 0; k < size - 1; k++)
{
if(num[k] > num[k+1])
{
holder = num[k];
num[k] = num[k+1];
num[k+1] = holder;
}
}
}
}
findLowtoHigh(size, num);
findHightoLow(size, num);
average = findAverage(size, num);
median = findMedian(size, num);
fprintf(stdout, "\n\nLowest Value: %3.4f", num[0]);
fprintf(stdout, "\nHighest Value: %3.4f", num[size-1]);
fprintf(stdout, "\n\nAverage Value: %3.4f\n", average);
fprintf(stdout, "Median Value: %3.4f", median);
fprintf(stdout, "\n");
}
}
int findSize()
{
int size;
fprintf(stdout, "\nPlease enter size of the array: ");
scanf("%d", &size);
return size;
}
void findLowtoHigh(int size, double num[])
{
fprintf(stdout, "\nFrom least to greatest: ");
for(int x = 0; x <= size - 1; x++)
{
fprintf(stdout, "%3.2f ", num[x]);
}
}
void findHightoLow(int size, double num[])
{
fprintf(stdout, "\nFrom greatest to least: ");
int reverse = size - 1;
while(reverse != -1)
{
fprintf(stdout, "%3.2f ", num[reverse]);
reverse--;
}
}
double findAverage(int size, double num[])
{
double average;
for(int a = 0; a <= size - 1; a++)
{
average = average + num[a];
}
average = average / size;
return average;
}
double findMedian(int size, double num[])
{
double median;
if(size % 2 == 0)
{
median = (num[size/2 - 1] + num[size/2])/2;
}
else
{
median = num[size/2];
}
return median;
}
答案 0 :(得分:2)
您必须初始化average
。改为
double average=0;
答案 1 :(得分:0)
使用(温和)优化编译您的prrogram并打开所有可重新启动的警告(gcc -O -Wall
是Linux的起点,clang
类似),并检查(并修复!)所有投诉编译器。只有这样你才能被问到'网。