2010-05-04 52 views
1

我更新了主要和sequetialSearch,現在它在運行時崩潰。它編譯好,但然後崩潰。計算搜索次數

的main.c

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <stdbool.h> 
#include "percentage.h" 
#include "sequentialSearch.h" 

#define searchAmount 100 

int main(int argc, char *argv[]) 
{ 
    int numbers[100]; 
    int searches[searchAmount]; 
    int testAmounts[searchAmount]; 
    int i; 
    int where; 
    int searchSuccess; 
    int searchUnsuccess; 
    int percent; 
    int looker; 
    int sum; 
    int average; 

    srand(time(NULL)); 
    for (i = 0; i < 100; i++){ 
     numbers[i] = rand() % 200; 
    } 
    for (i = 0; i < searchAmount; i++){ 
     searches[i] = rand() % 200; 
    } 

    searchUnsuccess = 0; 
    searchSuccess = 0; 
    sum = 0; 

    for(i = 0; i < searchAmount; i++){ 
     if(seqSearch(numbers, 100, searches[i], &where, &looker)){ 
       searchSuccess++; 
       testAmounts[i] = looker; 

     }else{ 
       searchUnsuccess++; 
       testAmounts[i] = looker; 
     } 
    } 
    for(i = 0; i < searchAmount; i++){ 
     sum = sum + testAmounts[i]; 
    } 

    average = sum/searchAmount; 

    percent = percentRate(searchSuccess, searchAmount); 
    printf("Total number of searches: %d\n", searchAmount); 
    printf("Total successful searches: %d\n", searchSuccess); 
    printf("Success Rate: %d%%\n", percent); 
    printf("Total number of tests ran: %d\n", average); 
    system("PAUSE"); 
    return 0; 
} 

sequentialSearch.h在

bool seqSearch (int list[], int last, int target, int* locn, int* looker){ 

    *looker = 0; 
    while(*looker < last && target != list[*looker]){ 
        *looker++; 
    } 

    *locn = *looker; 
    return(target == list[*looker]); 
} 

回答

2

通旁觀者引用,這樣就可以從呼叫者訪問其價值。

int looker; 

... 

for(i = 0; i < searchAmount; i++){ 
     if(seqSearch(numbers, 100, searches[i], &where, &looker)){ 
      searches[i] += looker; 
      searchSuccess++;  
     }else{ 
      searchUnsuccess++; 
     } 
} 


bool seqSearch (int list[], int last, int target, int* locn, int *looker){ 
    *looker = 0; 
    while(*looker < last && target != list[*looker]){ 
        (*looker)++; 
    } 

    *locn = *looker; 
    return(target == list[*looker]); 
} 

順便說一句,您可能希望重新考慮在頭文件中定義函數;如果您有多個包含此文件的c文件,則可能會在鏈接時出現重複符號問題。

+0

好吧,但我的主要問題是我怎麼把我的主要方式寫入數組? – shinjuo 2010-05-04 19:31:53

+0

哦,我明白了。謝謝 – shinjuo 2010-05-04 19:33:16

+0

對不起,更新了我的答案給你。 – WhirlWind 2010-05-04 19:33:51

1

爲什麼不直接傳遞looker作爲int*,用它基本上與你一直,看值之後seqSearch(...)回報,並把它添加到正在運行的總回main()

1

一個問題是seqSearch中的looker增量正在遞增指針而不是值。它可能應該是:

(*looker)++;