#include <stdio.h>
/*
2015-02-09
题目:1-13
难度系数:*****
打印输入中单词长度的直方图。即:长度为1的单词有?个,长度为2的单词有?个,,,长度为10的单词有?个
直方图要有最高的长度限制
单词也要有最长的限制
难点为输出垂直直方图时,要理解控制方式。
*/
#define IN 1
#define OUT 0
#define MAXHIST 15
#define MAXWORD 11
void print_horizontal_histogram();
void print_vertical_histogram();
int main()
{
print_horizontal_histogram();
print_vertical_histogram();
return 0;
}
void print_horizontal_histogram()
{
int c, i, nc, state, maxvalue, len, ovflow;
int wl[MAXWORD]; //记录长度为i的单词的数目,i=1,2,3,4,5,,,10
nc = 0; //记录当前输入的单词长度
state = OUT;
maxvalue = 0;
ovflow = 0;
for(i = 1; i < MAXWORD; ++i)
wl[i] = 0;
while((c = getchar()) !=EOF)
{
if(c == ' ' || c == '\t' || c == '\n')
{
if(nc > 0)
{
if(nc < MAXWORD)
{
++wl[nc]; //一个单词的终结
state = OUT;
}
else
{
++ovflow;
}
nc = 0;
}
}
else if(state == OUT)
{
nc = 1;
state = IN; //一个单词的开始
}
else
++nc;
}
for(i = 1; i < MAXWORD; ++i)
{
if(maxvalue < wl[i])
maxvalue = wl[i];
}
for(i = 1; i < MAXWORD; ++i)
{
printf("%d\t%d\t", i, wl[i]);
if(wl[i] > 0)
{
len = wl[i] * MAXHIST / maxvalue;
if(len < 1)
len = 1;
}
else
len = 0;
while(len > 0)
{
putchar('*');
--len;
}
putchar('\n');
}
if(ovflow > 0)
printf("There are %d words >= %d\n", ovflow, MAXWORD);
}
void print_vertical_histogram()
{
int c, i, j, nc, state;
int maxvalue;
int ovflow;
int wl[MAXWORD];
state = OUT;
nc = 0;
ovflow = 0;
maxvalue = 0;
for(i = 0; i < MAXWORD; ++i)
wl[i] = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '\t' || c=='\n')
{
state = OUT;
if(nc > 0)
{
if(nc < MAXWORD)
++wl[nc];
else
++ovflow;
nc = 0;
}
}
else
{
if(state == OUT)
{
state = IN;
nc = 1;
}
else
++nc;
}
}
for(i = 1; i < MAXWORD; ++i)
{
if(maxvalue < wl[i])
maxvalue = wl[i];
}
//some nice codes 控制输出为一个垂直方向的直方图
for(i = MAXHIST; i > 0; --i) //从图形最上端逐行向下扫描
{
for(j = 1; j < MAXWORD; ++j) //每行都从左至右扫描
{
if(wl[j] * MAXHIST / maxvalue >= i)
printf(" * ");
else
printf(" ");
}
putchar('\n');
}
for(i = 1; i < MAXWORD; ++i) //输出wl[]各个元素的下标
printf("%3d ", i);
putchar('\n');
for(i = 1; i < MAXWORD; ++i) //输出wl[]各个元素的取值
printf("%3d ", wl[i]);
putchar('\n');
if(ovflow > 0)
printf("There are %d words >= %d\n", ovflow, MAXWORD);
}
/*
what does not
kill you
make you
stronger .
^Z
1 1 ***
2 0
3 3 ***********
4 4 ***************
5 0
6 0
7 0
8 1 ***
9 0
10 0
what does not
kill you
make you
stronger .
^Z
*
*
*
*
* *
* *
* *
* *
* *
* *
* *
* *
* * * *
* * * *
* * * *
1 2 3 4 5 6 7 8 9 10
1 0 3 4 0 0 0 1 0 0
--------------------------------
Process exited after 47.99 seconds with return value 0
请按任意键继续. . .
*/
C程序设计语言,第一章
最新推荐文章于 2024-07-06 10:06:12 发布