/*水平方向的直方图*/
1 #include <stdio.h>
2 #define MAXHIST 15
3 #define MAXWORD 11
4 #define IN 1
5 #define OUT 0
6
7 int main()
8 {
9
10 int c, i, nc, state;
11 int len;
12 int maxvalue;
13 int ovflow;
14 int wl[MAXWORD];
15
16 state = OUT;
17 nc = 0;
18 ovflow = 0;
19 for (i = 0; i < MAXWORD; ++i)
20 wl[i] = 0;
21 while((c = getchar()) != EOF)
22 {
23 if(c == ' ' || c == '\n' || c == '\t')
24 {
25 state = OUT;
26 if (nc > 0)
27 if (nc < MAXWORD)
28 ++wl[nc];
29 else
30 ++ovflow;
31 nc = 0;
32 }
33 else if (state == OUT)
34 {
35 state = IN;
36 nc = 1;
37 }
38 else
39 ++nc;
40 }
41 maxvalue = 0;
42 for (i = 1; i < MAXWORD; ++i)
43 if (wl[i] > maxvalue)
44 maxvalue = wl[i];
45 for (i = 1; i < MAXWORD; ++i)
46 {
47 printf("%5d - %5d :", i, wl[i]);
48 if (wl[i] > 0)
49 {
50 if ((len = wl[i] * MAXHIST / maxvalue) <= 0)
51 len = 1;
52 }
53 else
54 len = 0;
55 while (len > 0)
56 {
57 putchar('*');
58 --len;
59 }
60 putchar('\n');
61 }
62 if (ovflow > 0)
63 printf ("There are %d words >= %d\n", ovflow, MAXWORD);
64 }
/*垂直方向的直方图*/
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define Word_IN 1 /* 在单词内*/ 5 #define Word_Out 0 /* 在单词外*/ 6 7 #define MaxWordLen 15 //单词的最大长度 8 9 void vertical(int a[] ,int n); 10 11 int main() 12 { 13 int c,i,j,wordLength; 14 int overflowWord = 0; //单词长度超过单词的最大长度的个数 15 //存放不同长度的单词个数. 单词长度为1的存放在 wordGraph[0] 16 int wordGraph[MaxWordLen]; 17 18 //初始化数组 19 for(i = 0; i< MaxWordLen; ++i){ 20 wordGraph[i] = 0; 21 } 22 23 int state = Word_Out; //初始在单词外 24 while((c = getchar()) != EOF){ 25 if(c ==' ' || c == '\t' || c == '\n'){ 26 if(state == Word_IN){ //遇到空格和制表符判断是否在单词内 27 if(wordLength <= MaxWordLen){ 28 wordGraph[wordLength - 1]++; 29 state = Word_Out; 30 } 31 else{ 32 ++overflowWord; 33 } 34 wordLength = 0; //清除单词的长度,为统计下一个单词做准备. 35 } 36 } 37 else{ 38 state = Word_IN; 39 ++wordLength; //在单词内,单词长度+1 40 } 41 } 42 //调用函数 43 vertical(wordGraph,MaxWordLen); 44 printf("\nThe overflow wrod num is:%d",overflowWord); 45 } 46 47 //打印垂直直方图 48 void vertical(int a[],int n){ 49 //1.寻找直方图最大值 50 int i,j,max=0; 51 for(i=0;i<n;++i){ 52 if(a[i]>max){ 53 max =a[i]; 54 } 55 } 56 //2.值为0的不打印 57 //外循环打印 y轴 高度 58 //内循环打印 x轴 59 for(i = max;i > 0; --i){ //从值最大的开始打印 60 for(j = 0;j < n; ++j){ 61 if(a[j] != 0){ //如果值为0,说明不存在此长度的单词,不打印 62 if(a[j] >= i){ 63 printf("** "); 64 } 65 else{ 66 printf(" "); 67 } 68 } 69 } 70 printf("\n"); 71 } 72 //打印单词的长度 73 for(j = 0;j < n; ++j){ 74 if(a[j] != 0){ 75 printf("%-4d",j + 1); 76 } 77 } 78 printf("\n"); 79 //打印各个单词长度的个数 80 for(j = 0;j < n; ++j){ 81 if(a[j] != 0){ 82 printf("%-4d",a[j]); 83 } 84 } 85 }
在gcc编译器里输入字符结束串结束EOF为:CTRL+D