2

また、boolを使用したためにエラーが発生するのはなぜですか?

この順次検索アルゴリズムを使用する必要がありますが、その方法がよくわかりません。配列で使用する必要があります。誰かが私を正しい方向に向けることができますか、これを使用する方法について何か。

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]);
}
4

4 に答える 4

1

このように使用するようです...

// I assume you've set an int list[], an int listlen and an int intToFind

int where;
bool found = seqSearch(list, listlen - 1, intToFind, &where);
if (found)
{
    // list[where] is the entry that was found; do something with it
}
于 2010-05-04T06:27:07.367 に答える
1

いくつかの問題があります。

  1. ラストの名前をサイズに変更します。
  2. 値が見つからない場合は、無効なメモリ ロケーションを逆参照します。

編集:最後はlength - 1. 珍しいサインですね。したがって、呼び出しは次のようになります。

int list[CONSTANT];
...
int foundIndex;
bool found = seqSearch(list, sizeof(list)/sizeof(int), target, &foundIndex);

bool を有効にする方法はたくさんあります。stdbool.h1 つはC99で使用することです。

于 2010-05-04T06:19:42.003 に答える
1

それはかなり明確です

list[]は検索対象のリストです は検索対象 lastの最後のインデックスlist targetです は検索対象が見つかっlist locn たインデックスが含まれます戻り値はが見つかっtargetたかどうかを示すブール値ですtarget

locnを渡す方法についての質問については、次のようにします

int locn; /* the locn where the index of target will be stored if found */

bool target_found = seqSearch(blah blah blah, &locn);
于 2010-05-04T06:22:01.730 に答える
1

コードの問題は、配列に存在しない要素を検索した場合lookerに等しくなり、無効なlast場所で配列要素にアクセスしようとすることです。last

代わりに、次のことができます。

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

    int looker;

    for(looker=0;looker<last;looker++) {

        // target found.
        if(list[looker] == target) {
            *locn = looker; // copy location.
            return true;    // return true.
        }
    }

    // target not found.
    *locn = -1;   // copy an invalid location.
    return false; // return false.
}

次のように関数を呼び出します。

int list[] = {5,4,3,2,1}; // the array to search in.
int size = sizeof(list)/sizeof(list[0]); // number of elements in the array.
int target = 3; // the key to search for.
int locn; // to hold the location of the key found..and -1 if not found.

if( seqSearch(list,size,target,&locn) ) {
  // target found in list at location locn.
} else {
  // target not found in list.
}
于 2010-05-04T06:22:26.187 に答える