计算搜索次数

时间:2010-05-04 19:27:09

标签: c search count

我更新了我的main和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]);
}

3 个答案:

答案 0 :(得分:2)

通过引用传递looker,以便您可以从调用者访问其值。

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文件,这可能会在链接时导致重复符号出现问题。

答案 1 :(得分:1)

为什么不将looker作为int*传递,基本上按照原样使用它,查看seqSearch(...)返回后的值,然后将其添加到运行总计中main()

答案 2 :(得分:1)

一个问题是seqSearch中的外观增量正在递增指针而不是值。应该是:

(*looker)++;