本文介绍了查找均值,中位数而不使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在不使用C的数组的情况下找到一组数字的均值,平均值?问题不是查找均值或中位数的方法,而是如果不允许使用数组,如何存储一组数字并对它们执行一些运算?
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 ?
推荐答案
一个有趣的问题.
找到存储所有数字的位置的键.代码可以使用文件,链接列表等.下面使用链接列表和递归.
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.
当count
为偶数时,将其留给OP进行多种模式或中值的细化.
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;
}
输入4 3 4 2 4 1 EOF
输出:
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参考: STD快速计算方法
这篇关于查找均值,中位数而不使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!