繁体   English   中英

C 要求用户输入后返回直方图的程序无法继续

[英]C program to return a histogram can't proceed after asking for user input

该程序的目标是返回一个直方图,计算具有 num_elts 成员的数据数组中值的出现次数。 但是,它停留在收集用户输入。

int *make_hist(int data[], int num_elts, int maxval) {
  int *hist = (int *)malloc(maxval * sizeof(int));
  int i = 0;
  while (i <= num_elts) {
    int val = data[i];
    if (val >= 0 && val <= maxval) {
      hist[val]++;
    }
  }
  return hist;
}

int main(void) {
  int values[20];
  printf("enter 20 integer values in the range 0-10\n");
  for (int i = 0; i < 20; i++) {
    scanf("%d", &values[i]);
  }
  int *result = make_hist(values, 20, 10);
  printf("occurrences:\n");

  for (int i = 0; i <= 10; i++) {
    printf("%d: %d\n", i, result[i]);
  }

  return 0;
}

你的int *make_hist(int data[], int num_elts, int maxval) function 中有一个无限循环,在while (i <= num_elts)部分。 您没有更改i的值,因此i (0) 将始终小于num_elets (20)。 我建议在 while 循环结束前添加++ii++来更新它。

int *make_hist(int data[], int num_elts, int maxval) {
     int *hist = (int *)malloc(maxval * sizeof(int));
     int i = 0;
     while (i <= num_elts) {
        int val = data[i];
        if (val >= 0 && val <= maxval) {
           hist[val]++;
        }
        ++i;
     }
     return hist;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM