求平均值,不使用数组的中位数

时间:2014-11-23 16:00:35

标签: c arrays pointers storage mean

如何在不使用C中的数组的情况下找到一组数字的均值,中位数? 问题不是找到均值或中位数的方法,而是如果不允许使用数组,如何存储一组数字并对它们执行某些操作?

1 个答案:

答案 0 :(得分:0)

一个有趣的问题。

找到存储所有数字的地方的关键。代码可以使用文件,链表等。下面使用链表和递归。

count为偶数时,将其留给OP进行有关多个模式或中位数的细化。

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", &current.x) == 1) {
    num_T *p = &current;
    // 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(&current);
  // 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
输出:

Count = 6
Mode = 4.000000  Count 3
Mean = 3.000000
STD  = 1.130388
Median = 3.000000

STD Ref:STD Rapid calculation methods