打印输入中各字符出现次数的直方图

 //转自K&R的《C程序设计语言》
 
#include <stdio.h>

#define NUM_CHARS 256    //0<=char<=255
 
int main(void)
{
   int c;
   long freqarr[NUM_CHARS + 1]={0};
 
   long thisval = 0;   //当前字符的统计个数
   long maxval = 0;     //所有字符的统计个数的最大值
   int thisidx = 0;
 
 
   while((c = getchar()) != EOF)
   {
   if(c < NUM_CHARS)
   {
      thisval = ++freqarr[c];
      if(thisval > maxval)
      {
      maxval = thisval;
      }
   }
   else
   {//不属于256个字符的统一算为另一类
      thisval = ++freqarr[NUM_CHARS];
      if(thisval > maxval)
      {
      maxval = thisval;
      }
   }
   }
 
   for(thisval = maxval; thisval > 0; thisval--)
   {
  printf("%4d  |", thisval);
  for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)
  {
   if(freqarr[thisidx] >= thisval)
   {
    printf("*");
   }
   else if(freqarr[thisidx] > 0)  // 只统计出现过的字符,未出现的字符个数为0,不打印
   {
    printf(" ");
   }
  }
  printf("\n");
   }
   printf("      +");
   for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)
   {
  if(freqarr[thisidx] > 0)
  {
    printf("-");
  }
   }
   printf("\n       ");
   //最后三行打印出现字符的ASCII码代码
   for(thisidx = 0; thisidx < NUM_CHARS; thisidx++)
   {
  if(freqarr[thisidx] > 0)
  {
    printf("%d", thisidx / 100);
  }
   }
   printf("\n       ");
   for(thisidx = 0; thisidx < NUM_CHARS; thisidx++)
   {
  if(freqarr[thisidx] > 0)
  {
    printf("%d", (thisidx - (100 * (thisidx / 100))) / 10 );
  }
   }
   printf("\n       ");
   for(thisidx = 0; thisidx < NUM_CHARS; thisidx++)
   {
  if(freqarr[thisidx] > 0)
  {
    printf("%d", thisidx - (10 * (thisidx / 10)));
  }
   }
   if(freqarr[NUM_CHARS] > 0)
   {
  printf(">%d\n", NUM_CHARS);
   }
 
   printf("\n");
 
   return 0;
}

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