我怎么知道用户写了多少个数字呢?

时间:2015-11-27 18:16:21

标签: c for-loop while-loop

我需要编写一个接受系列长度(0和1)并且用户编写系列的函数。该函数告诉最长相同太阳系的位置。

实施例: 函数获取长度= 12,用户写入:1 0 0 1 1 1 1 0 0 0 1 1 这个问题的答案是4,因为最长的组合(连续四个1' s)从第4位开始。

另一个例子: 长度为:12,用户输入:1 0 0 0 1 1 0 1 1 1 0 0 这个问题的答案是2(连续三个0'从第2位开始 - 如果有多个子系列长度相同则返回第一个。)

这就是我试图做的事情:

int sameNumbers(int seriaLength)
{
    int i;
    int place=0;
    int num1, num2;
    int sameCount;
    int maxSameCount = 0;

    printf("Please enter the seria: \n");
    scanf("%d",&num1);

    for(i = 1; i < seriaLength; i++)
    {
        scanf("%d",&num2);
        while(num1 == num2)
        {
            sameCount++;
        }
        if(sameCount > maxSameCount)
        {
            maxSameCount = sameCount;
            place = i;
        }
        scanf("%d",&num1);
    }

    return place;
}

编辑: 我需要在没有数组的情况下这样做。

谢谢!

1 个答案:

答案 0 :(得分:1)

这似乎做你想要的。要理解逻辑,请参阅代码中的注释。

#include <stdio.h>
int sameNumbers(int seriaLength)
{

    int i, num, previousNum, length = 0, maxLength = 0, start = 0, startOfLongest = 0;

    printf( "Please enter the series: " );

    for( i = 0; i < seriaLength; i++ )
    {
        scanf( "%d", &num );

        if( i > 0 && num == previousNum ) length++;
        else { length = 1; start = i; }  // if the number is not the same as the previous number, record the start of a new sequence here
        if( length > maxLength ) { maxLength = length; startOfLongest = start; } // if we've broken (not equalled) the previous record for longest sequence, record where it happened
        previousNum = num;
    }
    return startOfLongest + 1; //  add 1 because the OP seems to want the resulting index to be 1-based
}

int main( int argc, const char * argv[] )
{
    printf( "%d\n", sameNumbers( 12 ) );
    return 0;
}