The C Programming Language 不同于书中题目答案的解答( Exercise 1-13)

Exercise 1-13. 

Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

<pre name="code" class="html">#include<stdio.h>
#define MAXHIST 15            /*max length of histogram */
#define MAXWORD	11            /*max length of a word*/
#define IN      1 <span style="white-space:pre">		</span>/*inside a word*/
#define OUT 	0  <span style="white-space:pre">		</span>/*outside a word*/
/*  print a vertical histogram  */ 
main()
{
	int c,i,j,nc,state;
//	int maxvalue;       
	int ovflow;<span style="white-space:pre">		</span>/× number of overflow words */
	int wl[MAXWORD];<span style="white-space:pre">	</span>/× word length counters */
	state=OUT;
	nc=0;              <span style="white-space:pre">	</span>/* number of chars in a word */
	ovflow=0;<span style="white-space:pre">		</span>/*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;    <span style="white-space:pre">	</span>/*beginning of a new word*/
		}
		else 
			++nc;<span style="white-space:pre">		</span>/* inside a word */
	}
//	maxvalue=0;          个人觉得没必要找出数组wl[]中的最大值
//	for(i=1;i<MAXWORD;++i)
//		if(wl[i]>maxvalue)
//			maxvalue=wl[i];
	for(i=MAXHIST;i>0;--i) 
	{
		for(j=1;j<MAXWORD;++j)
		<span style="white-space:pre">	</span>if((wl[j]+MAXHIST)%MAXHIST>=i) /* 取代原答案 if(wl[j]*MAXHIST/maxvalue>=i)*/
				printf(" *");
			else 
				printf("  ");
		putchar('\n');
	}
	for(i=1;i<MAXWORD;++i)
		printf("%2d",wl[i]);
	putchar('\n');
	for(i=1;i<MAXWORD;++i)
		printf("%2d",i);
	putchar('\n');
	if(ovflow>0)
		printf("There are %d words >= %d\n",ovflow,MAXWORD);
}


 

编译结果如下:


原答案的编译结果是:


感觉不够直观!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值