我正在尝试编写一个程序,将每个单词的长度存储在一个
数组并打印出来。但是长度 n
没有打印出来,而是打印出长度 n - 1
。
#include <stdio.h>
#define IN 1
#define OUT 0
#define MAXLENGTH 10
int main(void)
{
int i, c, state, word;
int array[MAXLENGTH];
state = OUT;
word = 0;
for (i = 0; i < MAXLENGTH; i++)
array[i] = 0;
while ((c = getchar()) != EOF)
{
if (c == '\n' || c == ' ')
state = OUT;
else if (state == IN)
{
++array[word];
}
else if (state == OUT)
{
state = IN;
++word;
}
}
for (i = 1; i < MAXLENGTH; i++)
if (array[i] != 0)
printf("cuvantu %d are %d caractere \n", i, array[i]);
}
最佳答案
考虑这段代码:
if (c == '\n' || c == ' ')
state = OUT;
else if (state == IN)
{
++array[word];
}
else if (state == OUT)
{
state = IN;
++word;
}
当 c
是换行符或空格时,它会将状态更改为 OUT
,大概意思是在单词之外。
当c
是另一个字符时:
- 如果状态为
IN
,它通过递增array[word]
来计算字符数,它跟踪当前单词的长度。 - 如果状态为
OUT
,它将状态更改为IN
并递增word
以开始计算一个新单词。
在最后一种情况下,不计算当前字符——不对 array[word]
执行递增。要解决此问题,请在最后一种情况下插入 ++array[word];
:
if (c == '\n' || c == ' ')
state = OUT;
else if (state == IN)
{
++array[word];
}
else if (state == OUT)
{
state = IN;
++word;
++array[word];
}
关于c - 为什么数组元素存储的是 n-1 而不是 n 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063582/