练习1-13

打印出输入单词的直方图

print histogram for words count

用水平方法打印

horizontal

#include <stdio.h>
/* Draw a histogram for words count 
   with horizontal V1.0 */

#define IN 1
#define OUT 0
int main()
{
	int c, i, j, state, nw, nc;
	int nlen[46];  //word max is 46.
	
	nw = 0;
	for (i = 0; i < 46; ++i)
		nlen[i] = 0;
	state = OUT;
	nc = OUT;
	while ((c = getchar()) != EOF){
		if (c == ' ' || c == '\t' || c == '\n'){
			if (nc > 0)
				++nlen[nc];
			state = OUT;
			nc = OUT;
		}	
		else if (state == OUT){
			state = IN;	
			++nw;
		}
		if (state == IN && (c != ' ' || c != '\t' || c != '\n'))
			++nc;
	}
	
	printf("words = %d\n", nw);
	
	for (i = 0; i < 46; ++i){
		if (nlen[i] > 0){
			if (i < 10)
				printf("%d  ", i);
			else
				printf("%d ", i);
			
			for (j = 0; j < nlen[i]; ++j)
				printf("#");
			printf("%d\n", j);
		}
		
	}	
}

用垂直方法打印

vertical

#include <stdio.h>
/* This is a program that draw histogram for word count with vertical */
#define IN 1
#define OUT 0
int main()
{
	int c, i, nw, nc, state, nmax;
	int nlen[18];  //words max 18
	
	nw = nc = nmax = 0;
	state = OUT;
	
	for (i = 0; i < 18; ++i)
		nlen[i] = 0;
	
	while ((c = getchar()) != EOF) {
		if (c == ' ' || c == '\n' || c == '\t') {
			state = OUT;
			if (nc > 0)
				++nlen[nc];
			nc = OUT;
		}
		else if (state == OUT) {
			++nw;
			state = IN;
		}
		
		if  (state == IN) {
			++nc;
		}
	}
	
	printf("words = %d\n", nw);
	
	for (i = 0; i < 18; ++i)
		if (nmax < nlen[i])
			nmax = nlen[i];
	
	printf("%d\n", nmax + 2);
	
	printf("%d\n", nmax + 1);
	
	while (nmax >= 0) {
		if (nmax >= 10)
			printf("%d ", nmax);
		else
			printf("%d  ", nmax);
		
		for (i = 0; i < 18; ++i) {
			if (nlen[i] >= nmax)
				printf(" ##");
			else
				printf("   ");
		}
		printf("\n");
		--nmax;
	}
	
	printf("   ");
	for (i = 0; i < 18; ++i)
		printf("%3d", i);
	printf("\n");
	
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值