c - 在 C 中使用 printf 格式化二进制搜索的输出?

标签 c printf binary-search

我在处理这个程序的输出时遇到了一些问题。我需要在一行上打印动词,并且在没有动词的情况下我需要打印一个单独的语句。对于前。

"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;
}

有什么想法吗?

最佳答案

它似乎工作正常,但你需要在周围添加括号

    if (position != -1)
        printf("The verbs are: %s\n", verbs[position]);
        check = 1;

喜欢

    if (position != -1) {
        printf("The verbs are: %s\n", verbs[position]);
        check = 1;
    }

否则循环中check总是置1。

如果您不想重复“The verbs are:”,请为此添加一个检查

    if (position != -1) {
        if (first) {
            printf("The verbs are:");
            first = 0;
            check = 1;
        }
        printf(" %s", verbs[position]);

    }

关于c - 在 C 中使用 printf 格式化二进制搜索的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16789585/

相关文章:

C - 找到极限之间的所有友好数字

go - 两种算法,我的机器上的结果相同,测试上的结果不同

algorithm - 二分搜索+排序与线性搜索(大O)

c - 循环二维数组中所有邻居对(2 点团)的高效算法

c - 如何检查字母表中的所有字母是否都在带有 C 的数组中(检查它是否是全字母表)

c - 为什么我的程序中第七个变量是6?

c - 是否可以随我的应用程序分发更新版本的 libc?

c++ - vsnprintf 崩溃程序,以防 %s 设置为整数

c - 如何在 C 中显示浮点除法的实际结果?

if-statement - Elixir 二分查找