C复习笔记(6)-6.24

6.24

 

A improve version for the answer book!

Notice:

int isprint ( int c );

Check if character is printable, I first use it to print the x-axis, then I found a extra variable, that’s the blank key, amazing! So, I used the isgraph()returns true for the same cases as isprint except for the whitespace characters (like ' '), which return true when checked with isprint but false when checked with isgraph.

 

#include <stdio.h>

 

/* NUM_CHARS should really be CHAR_MAX but K&R haven't covered that at this stage in the book */

#define NUM_CHARS 256

 

int main(void)

{

  int c;

  long freqarr[NUM_CHARS + 1];

 

  long thisval = 0;

  long maxval = 0;

  int thisidx = 0;

 

  for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)

  {

    freqarr[thisidx] = 0;

  }

 

  while((c = getchar()) != EOF)

  {

    if(c < NUM_CHARS)

    {

      thisval = ++freqarr[c];

      if(thisval > maxval)

      {

        maxval = thisval;

      }

    }

    else

    {

      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(isgraph(thisidx))

    {

        if(freqarr[thisidx] >= thisval)

        {

            printf("*");

        }

        else if(freqarr[thisidx] > 0)

        {

            printf(" ");

        }

    }

    }

    printf("/n");

  }

  printf("      +");

  for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)

  {

    if(freqarr[thisidx] > 0)

    {

      printf("-");

    }

  }

  printf("/n       ");

 

  /*print x-axis */

  for(thisidx = 0; thisidx < NUM_CHARS; thisidx++)

  {

    if(freqarr[thisidx] > 0)

    {

    if(isgraph(thisidx))

        putchar(thisidx);

    }

  }

  printf("/n       ");

 

  /*Deal this the extrmely situation*/

  if(freqarr[NUM_CHARS] > 0)

  {

      if(isgraph(NUM_CHARS))

         putchar(NUM_CHARS);

      printf("/n");

  }

 

  printf("/n");

 

  return 0;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值