C语言打印统计单词长度的直方图课后习题

#include

#define IN 1
#define OUT 0
#define MAXHIST 15 //直方图最长长度 
#define MAXWORD 11 //单词最长长度

main()
{
	int c,nc,i,j ;
	int state ;
	int maxvalue ;
	int ovflow ;
	int wl[MAXWORD] ;
	state = OUT ;
	nc = 0 ;
	ovflow = 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 ;
		}                                 // 开始一个单词,nc初始化 
		else 
			++ nc ;						 //在单词内部,统计单词长度								
		
	}
	maxvalue = 0 ;
	for(i = 1 ; i < MAXWORD ; ++ i)
		if(wl[i] > maxvalue)
			maxvalue = wl[i] ;
	for(j = MAXHIST ; j > 0 ; -- j){  
		for(i = 1; i < MAXWORD ; ++ i) 
			if(wl[i] * MAXHIST / maxvalue >= j)
				printf(" # ") ;
			else 
				printf("   ") ; 
		putchar('\n') ;
	}	
	
	for(i = 1 ; i < MAXWORD ; ++ i)
		printf( "%-3d" , i) ;
	putchar('\n') ;
	 
	for(i = 1 ; i < MAXWORD ; ++ i)
		printf( "%-3d" , wl[i]) ;
	putchar('\n') ;
	if(ovflow > 0)
 		printf("There are %d words >= %d\n", ovflow , MAXWORD) ;
}

你可能感兴趣的:(c语言)