2

私は「Cプログラミング言語」の本で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 に答える