码迷,mamicode.com
首页 > 编程语言 > 详细

C语言K&R习题系列——统计一段文字中各个字母出现的频率

时间:2015-03-15 07:12:11      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:c

原题:

/*Write a program to print a histogram of the frequencies of 

 *difficent characters in it inputs

 */


这个和上一个类似


输入部分

#include < stdio.h >
 
 #define NUM_CHARS 256
 
 main ( void )
 {
	int c;
	int done = 0;
	int thisIdx = 0;
	long frequrr[NUM_CHARS + 1];
	long thisVal = 0;
	long maxVal = 0;
	//initialize
	for ( thisIdx = 0; thisIdx <= NUM_CHARS; thisIdx++ )
	{
		frequrr[thisIdx] = 0;
	}
	
	while ( done == 0 )
	{
		c = getchar();
		
		if ( c == EOF )
		{
			done = 1;
		}
		
		if ( c < NUM_CHARS )
		{
			thisVal = ++frequrr[c];
			if ( thisVal > maxVal )
			{
				maxVal = thisVal;
			}
		}
		else 
		{
			thisVal = ++frequrr[NUM_CHARS];
			if ( thisVal > maxVal )
			{
				maxVal = thisVal;
			}
		}
	}


输出部分

for ( thisVal = maxVal; thisVal >0; thisVal-- )
	{
		printf ( "%2d |", thisVal );
		for ( thisIdx = 0; thisIdx <= NUM_CHARS; thisIdx++ )
		{
			if ( frequrr[thisIdx] >= thisVal )
			{
				printf ( "*" );
			}
			else if ( frequrr[thisIdx] > 0 )
			{
				printf ( " " );
			}
		}
		printf ( "\n" );
	}
	printf ( "   |_" );
	for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
	{
		if ( frequrr[thisIdx] > 0 )
		printf ( "_");
	}
	printf ( "\n    " );
	for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
	{
		if ( frequrr[thisIdx] > 0 )
		printf ( "%d", ( thisIdx + 1 ) / 100 );
	}
	printf ( "\n    " );
	for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
	{
		if ( frequrr[thisIdx] > 0 )
		printf ( "%d", ( thisIdx + 1 ) / 10 % 10 );
	}
	printf ( "\n    " );
	for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
	{
		if ( frequrr[thisIdx] > 0 )
		printf ( "%d", ( thisIdx + 1 ) % 10 );
	}
	printf ( "\n" );
	return 0;
 }
 
 
 运行结果

技术分享

本文出自 “hacker” 博客,请务必保留此出处http://anglecode.blog.51cto.com/5628271/1620416

C语言K&R习题系列——统计一段文字中各个字母出现的频率

标签:c

原文地址:http://anglecode.blog.51cto.com/5628271/1620416

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!