从头再学C语言:单词长度直方图

来源:互联网 发布:淘宝全球购买到假货 编辑:程序博客网 时间:2024/04/29 22:10

上周一直在准备操作系统的考试,所以C语言这边就没有什么进展。其实这样子是很不好的,电脑都有并发性,我却做不到。所有的编程语言里对C比较喜欢,但现在学着也有点着急,看一些招聘启事上都是要求C++、java、windows编程、linux等等,可我自己还在c语言基础这打转。怪之前根本不知道自己该学什么,也一直纠结与考试,到现在大三了才知道要学技术。可是后悔也没有用,还是去掉浮躁的心,一点点学吧,就算慢点,迟点,总有到达的时候,一直不行动,就会永远迟下去。

一上午主要是在做一个题目:

Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

先做的比较简单the histogram with the bars horizontal(额~,不知道中文该怎么说~),又做的vertical orientation 。后者的代码如下:#include "stdio.h"
#include "conio.h"
#define len 20
main()
{
    int c,i,m,pre;
    int num[12];
    for(i=0;i<12;i++)
       num[i]=0;
    m=pre=i=0;
    while((c=getchar())!=EOF)
    {    if (c!=' '&&c!='/t'&&c!='/n')
            { m=1;
              i++;
             }
         else
            {if( m == 1 )
                if(i<11)
                   num[i]++;
                else num[11]++;
              m=0;
              i=0;
              }
         pre=c;
   }
   if(pre!=' '&&pre!='/t'&&pre!='/n')
    num[i]++;
   for(i=len;i>0;i--)
   {printf("%3d| ",i);
     for(m=1;m<12;m++)
       if(num[m]>=i)
         printf("* | ");
       else
         printf("  | ");
    printf("/n");
  }
 
printf("   |");
   for(i=1;i<11;i++)
   printf(" %2d|",i);
printf(">10|/n" );}做完后和参考答案相比,除了对于最大单词量的设置方式上没有它好外,其他的还是比较不错的,当然有我没看出来的其他不足之处,欢迎批评指教。另外对答案中的firstletter这个变量的作用不太理解,我觉得它根本没有存在的必要,欢迎看到这篇笔记的朋友们讨论。
int main(void)
{
  int c;
  int inspace = 0;
  long lengtharr[MAXWORDLEN + 1];
  int wordlen = 0;
 
  int firstletter = 1;
  long thisval = 0;
  long maxval = 0;
  int thisidx = 0;
  int done = 0;
 
  for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++)
  {
    lengtharr[thisidx] = 0;
  }
 
  while(done == 0)
  {
    c = getchar();
 
    if(c == ' ' || c == '/t' || c == '/n' || c == EOF)
    {
      if(inspace == 0)
      {
        firstletter = 0;
        inspace = 1;
 
        if(wordlen <= MAXWORDLEN)
        {
          if(wordlen > 0)
          {
            thisval = ++lengtharr[wordlen - 1];
            if(thisval > maxval)
            {
              maxval = thisval;
            }
          }
        }
        else
        {
          thisval = ++lengtharr[MAXWORDLEN];
          if(thisval > maxval)
          {
            maxval = thisval;
          }
        }
      }
      if(c == EOF)
      {
        done = 1;
      }
    }
    else
    {
      if(inspace == 1 || firstletter == 1)
      {
        wordlen = 0;
        firstletter = 0;
        inspace = 0;
      }
      ++wordlen;
    }
  }

原创粉丝点击