0

我的函数在遇到 0 0 0 0 1 1 0 时应该有一个成功的启动序列,但是当我输入这些数字时,成功启动序列的数量不会改变但是这并不能阻止它编译,我不能我犯的错误在哪里。

main()

{
    int i,num;
    int array[300];
    i=0;
    num=0;
    while(i<100)
    {
        scanf("%d",&array[i]); //input


        i++;
        //checks for start sequences while making sure there is atleast 8 numbers input
        if((i>=8)&&((array[i-1])==0)&&((array[i-2])==1)&&((array[i-3])==1)&&((array[i-4])==0)&&     ((array[i-5])==0)&&((array[i-6])==0)&&((array[i-7])==0))
        {
            num++;//counts the number of successful startsequences

        }
    printf("Number of valid start sequences is %d\n",num);
    }
}
4

2 回答 2

4

您正面临一个错误。

n请记住,数组中的元素编号由n-1索引标记。

例如,

if((i>=8)&&((array[i-1])==0)&&((array[i-2])==1)&&((array[i-3])==1)&&((array[i-4])==0)&&     ((array[i-5])==0)&&((array[i-6])==0)&&((array[i-7])==0))

从不检查array[0]元素,是吗?

也许,你想从改变if((i>=8)开始if((i>=7)

于 2014-12-03T06:31:30.750 回答
1
this line that checks for the sequence,
which is probably where the problem is located
is very difficult to read.
suggest writing it like so:

if(   (i>=8)
   && (0 == array[i-1])
   && (1 == array[i-2])
   && (1 == array[i-3])
   && (0 == array[i-4])
   && (0 == array[i-5])
   && (0 == array[i-6])
   && (0 == array[i-7]))


now that the line is readable, it looks like the array offsets are not correct.
and when i = 8, then 8 items have been read, 
and the code is only checking the last 7 inputs
so to not miss the first possible matching sequence: 

I suspect the line should be:

if(   (i>=7)
   && (0 == array[i-0])
   && (1 == array[i-1])
   && (1 == array[i-2])
   && (0 == array[i-3])
   && (0 == array[i-4])
   && (0 == array[i-5])
   && (0 == array[i-6]))
于 2014-12-03T08:06:45.633 回答