【发布时间】:2015-02-06 17:28:25
【问题描述】:
我有以下 c 程序,它应该打印我们输入中单词长度的垂直直方图。
#include <stdio.h>
#define MAX_WORD_LENGTH 35 /* maximum word length we will support */
int main(void)
{
int i, j; /* counters */
int c; /* current character in input */
int length; /* length of the current word */
int lengths[MAX_WORD_LENGTH]; /* one for each possible histogram bar */
int overlong_words; /* number of words that were too long */
for (i = 0; i < MAX_WORD_LENGTH; ++i)
lengths[i] = 0;
overlong_words = 0;
while((c = getchar()) != EOF)
if (c == ' ' || c == '\t' || c == '\n')
while ((c = getchar()) && c == ' ' || c == '\t' || c == '\n')
;
else {
length = 1;
while ((c = getchar()) && c != ' ' && c != '\t' && c != '\n')
++length;
if (length < MAX_WORD_LENGTH)
++lengths[length];
else
++overlong_words;
}
printf("Histogram by Word Lengths\n");
printf("=========================\n");
for (i = 0; i < MAX_WORD_LENGTH; ++i) {
if (lengths[i] != 0) {
printf("%2d ", i);
for (j = 0; j < lengths[i]; ++j)
putchar('#');
putchar('\n');
}
}
}
我将它编译为 a.out,在我做的终端上 ./a.out,我输入一个单词,但没有任何反应。有什么帮助吗?我是 C 的新手,只是想学习。
【问题讨论】:
-
用缩进正确地格式化你的代码,并在你的大 if 和 while 上加上大括号。我根本无法遵循此代码。