码迷,mamicode.com
首页 > 其他好文 > 详细

C - The C Answer (2nd Edition) - Exercise 1-14

时间:2015-07-25 15:19:27      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:exercise 1-14

/* Write a program to print a histogram of the frequencies of different 
   characters in its input. */

#include <stdio.h>
#include <ctype.h>

#define MAXHIST 15    /* max length of histogram */
#define MAXCHAR 128   /* max different characters */

/* print horizontal histogram frequencies of different characters */
main()
{
	int c, i;
	int len;          /* length of each bar */
	int maxvalue;     /* maximum value for cc[] */
	int cc[MAXCHAR];  /* character counters */
	
	for(i = 0; i < MAXCHAR; ++i)
	{
		cc[i] = 0;
	}
	while((c = getchar()) != EOF)
	{
		if(c < MAXCHAR)
		{
			++cc[c];
		}
	}
	maxvalue = 0;
	for(i = 1; i < MAXCHAR; ++i)
	{
		if(cc[i] > maxvalue)
		{
			maxvalue = cc[i];
		}
	}
	
	for(i = 1; i < MAXCHAR; ++i)
	{
		if(isprint(i))
		{
			printf("%5d - %c - %5d : ", i, i, cc[i]);
		}
		else
		{
			printf("%5d -   - %5d : ", i, cc[i]);
		}
		if(cc[i] > 0)
		{
			if((len = cc[i] * MAXHIST / maxvalue) <= 0)
			{
				len = 1;
			}
		}
		else
		{
			len = 0;
		}
		while(len > 0)
		{
			putchar('*');
			--len;
		}
		putchar('\n');
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

C - The C Answer (2nd Edition) - Exercise 1-14

标签:exercise 1-14

原文地址:http://blog.csdn.net/troubleshooter/article/details/47056223

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