您的位置:首页 > 其它

打印输入单词长度的直方图 (水平方向)程序分析

2015-04-10 14:21 387 查看
程序来自《C程序设计语言第2版》——练习1-13,P17

编写一个程序打印输入中单词长度的直方图(水平方向)

程序:

#include <stdio.h>
#define MAXHIST    15           // max length of histogram  	直方图的最大长度
#define MAXWORD    11           // max length of a word     	单词的最大长度
#define IN         1            // inside a word            	在单词中
#define OUT        0            // outside a word           	在单词外

/* print horizontal histogram */
int main(void)
{
int c, i, nc, state;
int len;              // length of each bar       每一个直方图的长度
int maxvalue;        // maximum value for wl[]   	相同长度单词出现次数最多的值
int ovflow;          // number of overflow words 	长度大于或等于MAXWORD的单词的数量
int wl[MAXWORD];    // word length counters       按单词长度值0~11,统计输入中各长度的单词数,存放在wl数组中
state = OUT;
nc = 0;            //number of chars in a word    一个单词的字符的个数
ovflow = 0;       // number of words >= MAXWORD
for (i = 0; i < MAXWORD; ++i)
wl[i] = 0;
while ((c = getchar()) != EOF)
{
if ((c == ' ' || c == '\n' || c == '\t'))
{
state = OUT;
if (nc > 0)
if (nc < MAXWORD)
++wl[nc];
else
++ovflow;
nc = 0;
}
else if (state == OUT)
{
state = IN;
nc = 1;             // beginning of a new word
}
else
++nc;               /* inside a word
}
maxvalue = 0;
/* 找出同一长度的单词出现的最大次数 maxvalue */
for (i = 1; i < MAXWORD; ++i)
if (wl[i] > maxvalue)
maxvalue = wl[i];
for (i = 1; i < MAXWORD; ++i)
{
printf("%5d - %5d :", i, wl[i]);
if (wl[i] > 0)
{
if ((len = wl[i] * MAXHIST / maxvalue) <=0)
// len = wl[i] * MAXHIST / maxvalue--> 可以理解为 (wl[i] / maxvalue) * MAXHIST
len = 1;
}
else
len = 0;
while (len > 0)
{
putchar('*');
--len;
}
putchar('\n');
}
if (ovflow > 0)
printf("There are %d words >= %d\n", ovflow, MAXWORD);
return 0;
}

输入:hello hello hello word word word word a a a a a a a a

输出:

1 - 8 :***************

2 - 0 :

3 - 0 :

4 - 4 :*******

5 - 3 :*****

6 - 0 :

7 - 0 :

8 - 0 :

9 - 0 :

10 - 0 :
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐