2013-09-21 46 views
2

这是选自K & R A问题: -C-打印直方图

写程序打印在其input.It字的长度的直方图是容易得出与酒吧水平直方图;但垂直方向更具挑战性。

我不应该使用任何库函数,因为这只是一个教程介绍!

我写了下面的程序这样做,但它有一些缺陷: -

1)如果有字与字之间不止一个空格字符,如预期的程序不能正常工作。

2)如何知道'k'的最大值我的意思是如何知道输入中有多少单词?

下面是代码: -

#include<stdio.h> 
#include<ctype.h> 
#include<string.h> 
#include<stdlib.h> 
#define MAX_WORDS 100 

int main(void) 
{ 
    int c, i=0, k=1, ch[MAX_WORDS] = {0}; 

    printf("enter the words:-\n"); 

    do 
    { 
     while((c=getchar())!=EOF) 
     { 
      if(c=='\n' || c==' ' || c=='\t') 
       break; 
      else 
       ch[i]++; 
     } 
     i++; 
    } 
    while(i<MAX_WORDS); 

    do 
    { 
     printf("%3d|",k); 
     for(int j=1;j<=ch[k];j++) 
      printf("%c",'*'); 
     printf("\n"); 
     k++; 
    } 
    while(k<10); 
} 

回答

2

这个程序将正常工作,即使有两个词和numWords之间不止一个换行符会给你的话的号码。

#include <stdio.h> 
#include <stdbool.h> 

int main(void) 
{ 
    int ch, cha[100] = {0}, k = 1; 
    int numWords = 0; 
    int numLetters = 0; 
    bool prevWasANewline = true;  //Newlines at beginning are ignored 

    printf("Enter the words:-\n"); 
    while ((ch = getchar()) != EOF && ch != '\n') 
    { 
     if (ch == ' ' || ch == '\t') 
      prevWasANewline = true; //Newlines at the end are ignored 
     else 
     { 
      if (prevWasANewline)  //Extra nelines between two words ignored 
      { 
        numWords++; 
        numLetters = 0; 
      } 
      prevWasANewline = false; 
      cha[numWords] = ++numLetters; 
     } 

    } 

    do 
    { 
     printf("%3d|",k); 
     for(int j=0;j<cha[k];j++) 
      printf("%c",'*'); 
     printf("\n"); 
     k++; 
    } while(k <= numWords); 

    return 0; 
}  
+2

这个地狱是谁低估了这个。至少他/她应该发表评论。 – haccks

+1

+1只是为了反击downvote。奇迹般有效。 – syb0rg

+0

该程序是正确的,但我认为该程序不符合K&R execise的要求。您应该计算长度的频率。所以如果你有5个单词,比如'a a a',你会得到1:5,或者如果你有3个单词,比如'ab abc',你会回到1:1 2:1 3:1。因此长度:频率。 – runners3431