日期:2014-05-16 浏览次数:20720 次
1、补完本节直方图程序的main
函数,以可视化的形式打印直方图。例如上一节统计20个随机数的结果是:
0 1 2 3 4 5 6 7 8 9 * * * * * * * * * * * * * * * * * * * *
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 10 #define min 0 #define max 10 #define band 10 int a[N], histogram[band], i; int gen_rand(int bound) // 产生0~bound范围内的随机数 { srand(time(NULL)); for (i = 0; i < N; i++) a[i] = rand() % bound; return 0; } /* int howmany(int value) // 统计a中等于value的数的个数 { int count = 0; for (i = 0; i < N; i++) { if (value == a[i]) { ++count; } } return count; } */ char star(int i) { char star; if (i <= 0) star = ' '; else star = '*'; return star; } int get_max (int a, int b) // 返回a、b中的较大值 { if (a < b) a = b; return a; } int main() { gen_rand(band); int i = 0, histogram[10] = {0}; int max_histogram = 0; for (i = 0; i < N; i++) histogram[a[i]]++; for (i = 0; i < 10; i++) printf ("%d\t", i); //打印随机数 printf ("\n"); for (i = 0; i < 10; i++) { printf ("%d\t", histogram[i]); // 打印每个随机数的频数 max_histogram = get_max (histogram[i], max_histogram); } printf ("\n\n"); while (max_histogram>0) { for (i = 0; i < 10; i++) { printf ("%c\t", star(histogram[i])); //打印直方图 histogram[i] = histogram[i] - 1; } printf ("\n"); max_histogram--; } return 0; }