首页 > 代码库 > 按长度统计输入单词的出现频率,并以直方图的形式打印。

按长度统计输入单词的出现频率,并以直方图的形式打印。

1-13

#include <stdio.h>

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

int main()
{
int c, i ,nc, state; //当前字符, , ,状态
int len; //每个直方图的长
int maxvalue; //wl[]的最大值(单词最高频率)
int ovflow;//超出长度(MAXWORD)的单词数
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 == ‘\n‘ || c == ‘\t‘){
    state = OUT;
    if(nc > 0)
    if(nc < MAXWORD)
      ++wl[nc]; //在计数数组中根据单词词长自增出现该长度的频率。
    else
      ++ovflow; //超出长度的单词累加频率
    nc = 0;
  }else if(state == OUT){
    state = IN;
    nc = 1; //一个单词的开始
  }else
    ++nc;
}
maxvalue = http://www.mamicode.com/0;
for(i = 1; i < MAXWORD; i++){
  if(wl[i] > maxvalue) maxvalue = http://www.mamicode.com/wl[i]; //找出出现最高频率的单词
}
for(i = 1; i < MAXWORD; i++){
  printf("%5d - %5d : ", i, wl[i]); //单词长度,出现频率
  if(wl[i] > 0){
    if((len = wl[i] * MAXHIST /maxvalue) <= 0) //按比例显示直方图长度
      len = 1;
  }else
     len = 0;
  while(len > 0){ //显示直方图
    putchar(‘*‘);
    --len;
  }
  putchar(‘\n‘);
}
if(ovflow > 0)
  printf("There are %d words >= %d\n",ovflow, MAXWORD);
}

 

 

//=============对每个单词的长度直接打印直方图(不考虑出现频率)=============//

#include <stdio.h>
#include <ctype.h>
#define OUT 0 //无单词
#define IN 1 //标志有单词读入

int main()
{
  int cnt, in, state;//计字符数,当前字符,当前状态
  state = OUT;cnt = 0; 
  while((in = getchar()) != EOF){
    if(isalnum(in)){
      if(state == OUT){
        state = IN;
        cnt++;
      }else
        cnt++;
    }

  if(in == ‘ ‘|| in == ‘\n‘ || in == ‘\t‘){
    if(state == IN){
      state = OUT;
      while(cnt){
        putchar(‘*‘);
        cnt--;
      }
      putchar(‘\n‘);
      cnt = 0;
    }
  }
}
int c = 10000;
while(c--);

}