在C中生成直方图

鳄梨

我一直坚持用C语言创建此直方图。问题在于,任务是计算每个用户输入出现的频率。

对于:1 0 6 1 5 0 7 9 0 7->有3x 0、2x 1等。

然后,该事件必须转换为恒星,而不是事件的数量。我想我涵盖了第一步和第三步,但是我很难将数字转换为星星。我必须进行一个新的循环,还是使用当前的嵌套循环?我将永远感激任何能提供我一些见解的人。

所以我的练习是:

  1. 询问用户输入并存储在数组中
  2. 处理数组并生成直方图数组
  3. 将直方图显示为星星

我的密码

#include <stdio.h>

void printHistogram ( int *hist, int n );

int main() {
   int i, j;
   int inputValue;

   printf("Input the amount of values: \n");  
   scanf("%d", &inputValue);
   int hist[inputValue];

   printf("Input the values between 0 and 9 (separated by space): \n");
   for (i = 0; i < inputValue; ++i) {
    scanf("%d", &hist[i]);  
   }

    int results[10] = {0};

    // Processing data to compute histogram, see 5.17
    for (i = 0; i < 10; ++i) {   
      for(j = 0; j < inputValue; j++) {
         if ( hist[j] == i){
            results[i]++;
         }
      } 
   }

    printf("\n");
    printHistogram(hist, 10);

    return 0;
}

void printHistogram(int *hist, int n) {
      int i, j;
      for (i = 0; i < n; i++) {
      printf("[%d] ", i);
      for ( j = 0; j < hist[i]; ++j) {
      printf("*");
      }
      printf("\n");
   }
}

输入项

10
1 0 6 1 5 0 7 9 0 7

输出量

Input the amount of values: 
Input the values between 0 and 9 (separated by space): 

[0] *
[1] 
[2] ******
[3] *
[4] *****
[5] 
[6] *******
[7] *********
[8] 
[9] *******

输出应为:

Input the amount of values: 10
Input the values between 0 and 9 (separated by space):

[0] ***
[1] **
[2] 
[3] 
[4] 
[5] *
[6] *
[7] **
[8] 
[9] *
乌尔玛

正如@ rafix07评论,你只需要调用printHistogram(results, 10)代替printHistogram(hist, 10)

已经编译和测试过...作品

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章