题目:
编写一个程序,打印输入中各个字符出现频度的直方图。
自我解答:
分析:所有字符皆是以ASCII码进行编码,编码范围为0~127,所以可以创建一个charArray[127]的数组存放各个字符出现的次数。得到这个数组后再以练习1-13中的方式打印出直方图,注意考虑归一化的问题,文本某一字符出现频度很高时,也许这个值会很大,打印出的直方图字符也许会很长,此时需要归一化处理。
以水平直方图为例:
#include <stdio.h>
#define SYMBOL '*' //the symbol of histogram
#define NORMSIZE 100 //the size of normalization
int main()
{
unsigned int charArray[127] = {0};
int c;
while((c = getchar()) != EOF)
{
charArray[c]++;
}
double factor = 1.0;
unsigned int maxValue = 0;
int i,j;
for(i = 0; i < 127; i++)
{
if(charArray[i] > maxValue)
maxValue = charArray[i];
}
if(maxValue > NORMSIZE)
{
factor = (double)maxValue / NORMSIZE;
}
for(i = 0; i < 127; i++)
{
if(charArray[i] > 0)
{
if(i >= 0 && i < 32) //non-control char, print ASCII digit
printf("the char: %d\t", i);
else
printf("the char: %c\t", i);
if((unsigned int)(charArray[i] / factor) == 0)
putchar(SYMBOL);
else
{
for(j = 0; j < (unsigned int)(charArray[i] / factor); j++)
putchar(SYMBOL)