2014-12-03 48 views
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); 
    } 
} 
+0

? – 2014-12-03 06:32:57

+1

也許把'i> = 8'改成'i> = 7'? – JS1 2014-12-03 06:34:23

+0

這一行:'main()'會引發一個編譯器警告(你應該啓用所有警告),所以代碼沒有成功編譯。注意:即使主函數的聲明不正確,該行應該是:'int main()',編譯器會提示缺少'return(intValue)'語句的警告。 – user3629249 2014-12-03 07:48:37

回答

4

您正面臨着off-by-one錯誤。

記住,元件數目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)

+1

@JaleelKibs:另外,您修復差一錯誤後,如果考慮下列順序應爲兩次成功的啓動序列或不計:'0 0 0 0 1 1 0 0 0 0 1 1 0'(我不不知道這個答案 - 這取決於你的應用程序的要求)。如果你只做了這個答案中提到的簡單修正,那麼即使第一個序列的最後一個零被用作第二個序列的第一個零,程序也會將它計爲兩個開始序列。 – 2014-12-03 06:47:44

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]))