2013-01-11 47 views
0

我在做C中的運動,但我不知道爲什麼作爲第一個結果我一直-1(那是不可能的)。 我只有在交換之後纔有-1來協調數組。現在二進制搜索鍛鍊; Tibial

#include <stdio.h> 
#include <time.h> 
#include <stdlib.h> 

main(){ 
     int vet[100], cont[100]; 
     int i, c, f=100; 
     int swap; 
     int r=0; 
     int search; 

     srand(time(NULL)); 

     for(i=0;i<100;i++){ 
       vet[i]=rand()%100+1; 
     } 

     while(r==0){ 
       r=1; 
       for(i=0;i<100;i++){ 
         if(vet[i]>vet[i+1]){ 
           swap=vet[i+1]; 
           vet[i+1]=vet[i]; 
           vet[i]=swap; 
           r=0; 
         } 
       } 
     } 

     for(i=0;i<100;i++){ 
       printf("%d) %d\n", i+1, vet[i]); 
     } 

     i=0; 
     r=0; 
     printf("Inserisci numero da ricercare (1-10000) -> "); 
     scanf("%d", &search); 
     if(search>10000 || search<0){ 
       printf("Hai inserito un valore non valido\n"); 
     } 
     else{ 
       c=(i+f)/2; 
       while(vet[c]!=search && i<f){ 
         if(vet[c]<search){ 
           i=c+1; 
           c=(i+f)/2; 
         } 
         else if(vet[c]>search){ 
           f=c-1; 
           c=(i+f)/2; 
         } 

         if(vet[c]==search){ 
           cont[r]=c+1; 
           r++; 
         } 
       } 
       if(vet[c]!=search){ 
         printf("Non e\' stato trovato nessun valore %d", search◆ 
       } 
       else{ 
         for(i=0;i<r;i++){ 
           printf("%d\n", cont[i]); 
         } 
       } 
     } 
} 

我必須使用srand(time(NULL))我知道有更好的解決方案。 練習沒有完成,現在我正在努力解決這個錯誤,有人可以幫助我嗎?

編輯: 我使用OPENVMS編譯,鏈接和運行

+0

改變你似乎沒有要排序的數組。 – 2013-01-11 16:07:33

+1

@ H2CO3他在乞討中做了一種單一的氣泡排序迭代。當然,這是不夠的 –

+0

@izomorphius是的,我不考慮一個'k'長度數組的迭代排序。 – 2013-01-11 16:09:15

回答

6

你的問題很可能是在這裏:

for(i=0;i<100;i++){ 
    if(vet[i]>vet[i+1]){ 

i=99,並訪問vet[i+1],你是關閉的結束陣列。這個元素沒有定義,它可能只是僥倖,你沒有得到任何更糟糕的行爲。

編輯: 因此,解決辦法是在

for(i=0;i<99;i++){ 
     if(vet[i]>vet[i+1]){ 
+0

我對izomorphius感謝同樣的感謝;) – Mitro