2015年3月11日

C语言:编写一个程序,打印输入中单词长度的直方图。

第2版《C程序设计语言》,P17,练习1-13:编写一个程序,打印输入中单词长度的直方图。水平方向的直方图比较容易绘制,垂直方向的直方图则要困难些。

此题咋一看比较简单,而且也不难得出思路。难的是根据清晰的思路写出代码,并且写出漂亮的代码。所以这道题还是做了很久,并且参考了书上的解答。

我的代码(水平方向的直方图):

#include <stdio.h>
# define MAXHIST    15
# define MAXWORD    11
# define IN         1
# define OUT        0
main()
{
    int n, i, c, nc, ovflow, state;
    int wl[MAXWORD];
    nc = 0;
    ovflow = 0;
    state = OUT;
    for (i = 0; i < MAXWORD; ++i)
        wl[i] = 0;

    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\n' || c == '\t') {
            if (state == IN) {
                if (nc > MAXWORD)
                    ++ovflow;
                else
                    ++wl[nc - 1];
                state = OUT;
                nc = 0;
            }
        }
        else {
            ++nc;
            if (state == OUT)
                state = IN;
        }
    }

    for (i = 0; i < MAXWORD; ++i) {
        printf("%3d-%3d : ", i+1, wl[i]);
        for (n = 0; n < wl[i] && n < MAXHIST; ++n)
            putchar('*');
        putchar('\n');
    }

    if (ovflow > 0)
        printf("超过长度限制的单词个数为%d\n", ovflow);

    return 0;
}

书上的代码:

#include <stdio.h>

# define MAXHIST 15 /* max length of histogram */
# define MAXWORD 11 /* max length of a word */
# define IN 1       /* inside a word */
# define OUT 0      /* outside a word */

/* print horizontal historgram */
main()
{
    int c, i, nc, state;
    int len;                /* length of each bar */
    int maxvalue;           /* maximum value for wl[] */
    int ovflow;             /* number of overflow words */
    int wl[MAXWORD];        /* word length counters */

    state = OUT;
    nc = 0;                 /* number of chars in a word */
    ovflow = 0;             /* number of words >= MAXWORD */
    for (i = 0; i < MAXWORD; ++i)
        wl[i] = 0;

    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\n' || c == '\t') {
            state = OUT;
            if (nc > 0)
                if (nc < MAXWORD)
                    ++wl[nc];
                else
                    ++ovflow;
            nc = 0;
        } else if (state == OUT) {
            state = IN;
            nc = 1;         /* beginning of a new word */
        } else
            ++nc;           /* inside a word */
    }
    maxvalue = 0;
    for (i = 1; i < MAXWORD; ++i)
        if (wl[i] > maxvalue)
            maxvalue = wl[i];

    for (i = 1; i < MAXWORD; ++i) {
        printf("%dd - %5d : ", i, wl[i]);
        if (wl[i] > 0) {
            if ((len = wl[i] * MAXHIST / maxvalue) <= 0) /*此句没有完全理解*/
                len = 1;
        } else
            len = 0;
        while (len > 0) {
            putchar('*');
            --len;
        }
        putchar('\n');
    }
    if (ovflow > 0)
        printf("There are %d words >= %d\n", ovflow, MAXWORD);
}

书中的此题主要是演示数组的使用。过于细节的地方不必深究。

You may also like...

发表评论

电子邮件地址不会被公开。 必填项已用*标注


*