2

我正在用“The C Programming Language”一书学习 C,我正在尝试解决练习 1.13:

“编写一个程序来打印输入中单词长度的直方图。用水平条绘制直方图很容易;垂直方向更具挑战性。”

我编写了代码,但是当我按 CTRL+Z(文件结尾)时,它显示全零而不是单词的长度。

谁能给我一个提示我哪里出错了?

#include <stdio.h>

/* print a histogram of the length of words from input */
main()
{
    int c, i, wordn, space;
    int lengthn[20];

    wordn = space = 0;
    for (i = 0; i < 20; ++i)
        lengthn[i] = 0;

    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\t' || c == '\n')
            if (space == 1) {
                ++wordn;
                space = 0;
                ++i;
            }
        if (c != ' ' && c != '\t' && c != '\n') {
            ++lengthn[i];
            space = 1;
        }
    }
    printf("Length: ");
    for (i = 0; i < 16; ++i)
        printf("%d   ", lengthn[i]);
    printf("\n        --------------------------------------------------------------\n");
    printf("Word:   1   2   3   4   5   6   7   8   9   10   11   12   13   14   15\n");
}
4

3 回答 3

2

(因为 OP 要求提示,而不是解决方案)

那么......i这个循环之后等于什么?

for (i = 0; i < 20; ++i)
    lengthn[i] = 0;

接下来你会在哪里使用它?

于 2011-04-30T17:09:01.147 回答
1
for (i = 0; i < 20; ++i)     
    lengthn[i] = 0;

此循环之后的值i将是i=20

所以你必须在while循环之前 初始化i

于 2011-08-15T04:14:57.460 回答
0

我写了一个垂直方向的代码。我是 C 新手,所以可能代码不好。

#include <stdio.h>
#include <conio.h>

#define MAX_WORDS 100
#define IN 1
#define OUT 0

int maxlength(int length[], char num_of_word);

int main()
{
    char c,i,j,state,num_of_word;
    int length[MAX_WORDS];
    /*initialize length[]*/
        for(i=0;i<MAX_WORDS;i++){
        length[i]=0;
        }
    /* find the length of each word */
    num_of_word=0;
    while(num_of_word<MAX_WORDS && (c = getchar()) != EOF && c != 'a'){
        if(c != ' ' && c!= '\t' && c!= '\n'){
            state = IN;
            length[num_of_word]++;
        }else{
            if(state != OUT){
                state = OUT;
                num_of_word++;
            }
        }
    }
    /*   draw histogram            */
    for(i= maxlength(length[],num_of_word);i>0;i--){
        for(j=0;j<num_of_word;j++){
            if(length[j]<i){
                printf(" ");
            }else{
                printf("|");
            }
        }
        printf("\n");
    }
    /* print name of each column*/
    for(i=0;i<num_of_word;i++){
        printf("%d",i+1);
    }

    _getch();
    return(0);
}
/*sub-function that find the longest word */
int maxlength(int length[], char num_of_word){
    int i, max;
    max = length[0];
    for(i=1;i<num_of_word;i++){
        if(max<length[i]){
            max = length[i];
        }
    }
    return max;
}
于 2016-12-26T07:35:59.877 回答