Read ahead in an array to predict later outcomes in C [closed]

佐手、 提交于 2019-12-11 20:28:41

问题


Basically what I'm trying to ask is, is there anyway to read ahead in an array so that you could create a 'case' for it.

For ex: you array has only integers such as: 0 0 0 0 4 0 1 0 0 0 0 0 0 0 0 0 0 0 0 3

and what you want to try to do is create a coutdown till the next non zero number. Basically display the countdown. Is there any way to do this?


回答1:


This code:

#include <stdio.h>

int main(void)
{
    int array[] = { 0, 0, 0, 0, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, };

    int a_size  = sizeof(array) / sizeof(array[0]);

    int i = 0;
    while (i < a_size)
    {
        if (array[i] == 0)
        {
            int j;
            for (j = i; j < a_size; j++)
                if (array[j] != 0)
                    break;
            printf("%d\n", j - i);
            i = j;
        }
        else
            i++;
    }
    return 0;
}

produces this output:

4
1
12

If that's what you want, that's roughly what you need. If it is not what you want, you need to explain more clearly what it is that you want.


Revised code for revised expected output:

#include <stdio.h>

int main(void)
{
    int array[] = { 0, 0, 0, 0, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, };

    int a_size  = sizeof(array) / sizeof(array[0]);

    int i = 0;
    while (i < a_size)
    {
        if (array[i] == 0)
        {
            int j;
            for (j = i; j < a_size; j++)
                if (array[j] != 0)
                    break;
            int k = j - i;
            while (k > 0)
                printf(" %d", k--);
            i = j;
        }
        else
        {
            printf(" '");
            i++;
        }
    }
    putchar('\n');
    return 0;
}

Revised output:

 4 3 2 1 ' 1 ' 12 11 10 9 8 7 6 5 4 3 2 1 '


来源:https://stackoverflow.com/questions/20167106/read-ahead-in-an-array-to-predict-later-outcomes-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!