我在C中创建一个程序,它计算输入的每个单词中的字母数,然后将它们打印为直方图。我在这个程序中使用了很多for循环,我收到了以下错误:
letter_size_chart.c:35:37: error: expected expression
for (i = maximum; i >= MIN_CHARS; --i)
^
letter_size_chart.c:38:27: error: expected expression
for (j = MIN_CHARS; i <= MAX_CHARS; ++i)
^
letter_size_chart.c:48:23: error: expected expression
for (i = MIN_CHARS; i <= MAX_CHARS; i++)
^
letter_size_chart.c:50:23: error: expected expression
for (i = MIN_CHARS; i <= MAX_CHARS; i++)
^
4 errors generated.
我的循环中有什么导致这些错误?这是我的代码:
/*
sorts input by size of words into a histogram
*/
#define EOF -1
#define MAX_CHARS 10 /* max number of chars allowed in a word */
#define MIN_CHARS
#include<stdio.h>
#include<ctype.h>
int main()
{
int c, i, j, word_length, numbcountsize, maximum;
int numbcount[MAX_CHARS];
word_length = 0;
while ((c = getchar()) != EOF)
{
if (isalpha(c))
++word_length;
else
if (word_length != 0)
{
++numbcount[word_length - 1];
word_length = 0;
}
}
maximum = numbcount[0];
for (i = MIN_CHARS; i <= MAX_CHARS; i++)
if (numbcount[i - 1] > maximum)
maximum = numbcount[i];
for (i = maximum; i >= MIN_CHARS; --i)
{
printf("%d |", i);
for (j = MIN_CHARS; i <= MAX_CHARS; ++i)
{
if (j >= i)
printf(" * ");
else
printf(" ");
}
printf("\n");
}
printf(" | ");
for (i = MIN_CHARS; i <= MAX_CHARS; i++)
printf("_");
for (i = MIN_CHARS; i <= MAX_CHARS; i++)
printf("%d\n", i);
}
答案 0 :(得分:1)
当你使用空字符串#define
时,即
#define MIN_CHARS
它告诉预处理器从程序文本中删除 MIN_CHARS
的所有提及。实际上,你的循环看起来像这样:
for (i =; i <= 10; i++)
这是无效的,因此C编译器拒绝它。
为MIN_CHARS
提供值可解决此问题:
#define MIN_CHARS 2