今天上午就写了个直方图出来,比书上打印的好了点,书上将*打印在下面,我打印在上面了,呵呵,纪念一下:
[root@vm c-study]# cat -n histogram.c
1 #include
2 #include
3 #define N 20
4 int a[N];
5 void gen_random(int n)
6 {
7 int i;
8 for (i=0;i 9 a[i] = rand() % n;
10 }
11
12 int main(void)
13 {
14 int i,max,histogram[10];
15 /* init histogram[] */
16 for(i=0;i<10;i++)
17 histogram[i]=0;
18
19 /* generate the random numbers */
20 gen_random(10);
21
22 /* put times of 0-9 to array : histogram[] */
23 for (i=0;i 24 histogram[a[i]]++;
25
26 /* find the max num of histogram[] */
27 max=0;
28 for (i=0;i<10;i++)
29 {
30 if (histogram[i]>max)
31 max=histogram[i];
32 }
33 printf("max=%d\n",max);
34
35 /* print times of 0-9 */
36 for (i=0;i<10;i++)
37 printf("%d ",histogram[i]);
38 printf("\n");
39
40 /* print * */
41 for (i=0;i<10;i++)
42 histogram[i] = max-histogram[i];
43
44 for (i=0;i 45 {
46 int j;
47 for (j=0;j<10;j++)
48 {
49 if (histogram[j]>0)
50 printf(" ");
51 else
52 printf("* ");
53 histogram[j]--;
54 }
55 printf("\n");
56 }
57 /* print 0-9 - base numbers */
58 for (i=0;i<10;i++)
59 printf("%d ",i);
60 printf("\n");
61 }
输出结果如下:
[root@vm c-study]# ./a.out
max=5
2 1 3 3 0 2 5 2 0 2
*
*
* * *
* * * * * * *
* * * * * * * *
0 1 2 3 4 5 6 7 8 9
阅读(483) | 评论(0) | 转发(0) |