问题
How do i find mean , median of a set of numbers without using arrays in C? Question is rather not the way to find mean or median but how to store a set of numbers and perform some operations on them if use of arrays is not allowed ?
回答1:
A fun problem.
The key to to find a place to store all the numbers. Code could use a file, a linked list, etc. The below uses a linked list and recursion.
Leave it to OP for refinements about multiple modes or median when count
is even.
typedef struct num_S {
struct num_S *prev;
double x;
} num_T;
void GetNum(num_T *prev) {
num_T current;
current.prev = prev;
// If new number found ...
if (scanf("%lf", ¤t.x) == 1) {
num_T *p = ¤t;
// Sort new entry into list
while (p->prev != NULL && p->x < p->prev->x) {
double t = p->x;
p->x = p->prev->x;
p->prev->x = t;
p = p->prev;
}
GetNum(¤t);
// End of list -now process the list
} else {
unsigned ModeCount = 0;
double Mode = 0.0;
unsigned ModeCandidateCount = 0;
double ModeCandidate = 0.0 / 0.0;
unsigned Count = 0;
double SumX = 0.0;
double SumXX = 0.0;
num_T *p = current.prev;
while (p != NULL) {
Count++;
SumX += p->x;
SumXX += p->x * p->x;
if (p->x == ModeCandidate) {
ModeCandidateCount++;
} else {
ModeCandidateCount = 1;
ModeCandidate = p->x;
}
if (ModeCandidateCount > ModeCount) {
ModeCount = ModeCandidateCount;
Mode = p->x;
}
p = p->prev;
}
printf("Count = %u\n", Count);
if (Count > 0) {
printf("Mode = %lf Count %u\n", Mode, ModeCount);
printf("Mean = %lf\n", SumX / Count);
printf("STD = %lf\n", sqrt(Count * SumX - SumXX) / Count);
Count /= 2;
num_T *p = current.prev;
while (Count-- > 0) {
p = p->prev;
}
printf("Median = %lf\n", p->x);
}
fflush(stdout);
}
}
int main(void) {
GetNum(NULL);
return 0;
}
Input 4 3 4 2 4 1 EOF
Output:
Count = 6
Mode = 4.000000 Count 3
Mean = 3.000000
STD = 1.130388
Median = 3.000000
STD Ref: STD Rapid calculation methods
来源:https://stackoverflow.com/questions/27090961/find-mean-median-without-using-arrays