为什么数组元素存储n-1而不是n的值

时间:2019-05-09 16:12:05

标签: c arrays

我正在尝试编写一个程序,将每个单词的长度存储在 排列并打印。但是不会打印长度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]);
}

3 个答案:

答案 0 :(得分:0)

考虑以下代码:

    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];
    }

答案 1 :(得分:0)

这似乎是避免常见的一次性错误的好方法。

虽然可以通过多种方式解决,但以下代码段显示了如何修改发布状态机的逻辑,以便可以从头开始填充长度数组,而无需跳过第一个元素array[0],达到(但不超过)其最大大小。

#include <stdio.h>

#define IN 1
#define OUT 0
#define MAXLENGTH 16

int main(void)
{
    int array[MAXLENGTH] = {0};

    int c, state = OUT,   
        n_words = 0; //  <-- this name may better convey the purpose of this variable

    while ((c = getchar()) != EOF)
    {
        if (c == '\n' || c == ' ')  // <-- Consider isspace() and iscntrl() instead.
        {
            // We are between words.
            state = OUT;
        }
        else
        {
            // Check the current state before updating it.
            if ( state == OUT )
            {
                // A new word starts, but there might not be enough space.
                if ( n_words == MAXLENGTH )
                {
                    // Here, the rest of the stream is not consumed
                    ungetc(c, stdin);
                    break;     
                }
                ++n_words; 
            }
            state = IN;

            // Array indices are zero based, so the current word is:
            ++array[n_words - 1];
        }
    }

    if ( c != EOF )
        fprintf(stderr, "Sorry, out of space.\n");

    // You can use the actual number of read words to limit the extent of the loop
    printf(" %5s  %5s\n---------------\n", "Word", "Length");
    for (int i = 0; i < n_words; i++)
        printf("%5d  %5d\n", i + 1, array[i]);
}

该代码是可测试的here

答案 2 :(得分:-1)

尝试将第二个for循环更改为- for (i = 0; i < MAXLENGTH; i++)