0

このプログラムの出力に問題があります。動詞を 1 行に出力する必要があり、動詞がない場合は別のステートメントを出力する必要があります。たとえば。

"talk and walk"印刷する必要があります"The verbs are: talk walk"

その間、"hello there"印刷する必要があります"There are no verbs"

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

int binary_search(char *list_of_words[], int size, char *target){
    int bottom= 0;
    int mid;
    int top = size - 1;
    int found = 0;

    while(bottom <= top && !found){
        mid = (bottom + top)/2;
        if (strcmp(list_of_words[mid], target) == 0){
            //printf("%s found at location %d.\n", target, mid+1);
            found = 1;
        } else if (strcmp(list_of_words[mid], target) > 0){
            top    = mid - 1;
        } else if (strcmp(list_of_words[mid], target) < 0){
            bottom = mid + 1;
        }
    }
    if (found == 1)
        return mid;
    else
        return -1;
}

int main(int argc, char* argv[]){
    char *input = strtok(argv[1], " \"\n");
    char *verbs[5] = { "do", "make", "take", "talk", "walk" };
    int position;
    int check = 0;
    while (input != NULL) {
        //printf("%s\n", input);
        position = binary_search(verbs, 5, input);
        if (position != -1)
            printf("The verbs are: %s\n", verbs[position]);
            check = 1;
        input = strtok(NULL, " ");
    }
    if (check == 0){
        printf("There are no verbs\n");
    }
    return 0;
}

何か案は?

4

3 に答える 3

0

自分で検索を実装するのではなく、単に検索を実行することに関心がある場合 (つまり、「検索を実装する」ことが実際のタスクではないと想定している場合)、標準ライブラリのあまり知られていないヒーローを使用する必要がありますbsearch()

これには、入力データ (検索対象の配列) をソートする必要がありますが、すでにバイナリ検索を行っているため、ソートされているように見えることに注意してください。

于 2013-05-28T12:22:54.550 に答える