编写一个程序,打印输入中单词长度的直方图。水平方向的直方图比较容易绘制,垂直方向的直方图则要困难些。
# include <stdio.h>
# define IN 1
# define OUT 0
# define MAXLEN 10 /*定义单词的最大长度*/
/*print histogram of word length in input*/
main()
{
int c, i, j, nc, state, max; /*nc = number character*/
int lword [MAXLEN];
scanf ("%c", &c); /*获取c作为字符输入*/
for (i = 0; i < MAXLEN; ++ i)
lword [i] = 0;
nc = max = 0;
state = OUT;
while ((c = getchar()) != EOF)
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
state = IN;
++ nc;
}
else if (state == IN){
state = OUT;
++ lword [nc - 1]; /*递增以不同单词长度为下标的数组*/
if (max < lword [nc - 1])
max = lword [nc - 1]; /*寻找数组最大值,并赋予max。为后续打印垂直直方图做准备*/
nc = 0;
}
/*打印水平直方图*/
printf ("print histogram of word length in input\n");
printf ("horizontal version:\n");
for (i = 0; i < MAXLEN; ++ i){
printf ("%2d: ", i + 1);
for (j = 0; j < lword [i]; ++ j)
printf ("*");
printf ("\n");
}
printf ("\n");
/*打印垂直直方图*/
/*思路:设置i = max + 1 的行往下扫,j = 0的列往右扫*/
printf ("vertical version:\n");
for (i = max + 1; i > 0; -- i){
for (j = 0; j < MAXLEN; ++ j)
if (i == lword [j] + 1)
printf ("%3d", lword [j]); /*当i = 某列数组值 + 1时,输出当列数组值*/
else if (i <= lword [j])
printf (" *"); /*当i <= 某列数组值时,输出**/
else
printf (" "); /*当i > 某列数组值时,输出空格*/
printf ("\n");
}
for (i = 1; i <= MAXLEN; ++ i)
printf ("%3d", i);
}
运行结果