条件不成功

时间:2014-12-03 06:27:37

标签: c if-statement input while-loop off-by-one

我的功能应该在遇到时有一个成功的开始序列 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);
    }
}

2 个答案:

答案 0 :(得分:4)

您面临off-by-one错误。

请记住,数组中的元素编号nn-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)

答案 1 :(得分: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]))