有人可以解释为什么它不会在我的二分查找中执行最后一个if语句

时间:2017-10-10 21:29:50

标签: c if-statement binary-search

当我运行它并尝试搜索结构中不存在的名称时,它不执行else if语句,它什么都不做。

if(first <= last) {

        while(first<= last){

            middle = (first + last)/2;

            if(strcmp(name, pSRecord[middle]->LastNames) == 0){

                printf("The Following Record Was Found: \nName: %s %s \nStudent ID: %d \nStudent Grade: %d \n", pSRecord[middle]->FirstNames, pSRecord[middle]->LastNames, pSRecord[middle]->IDNums, pSRecord[middle]->Marks);
                exit(0);

            } else if (strcmp(name, pSRecord[middle]->LastNames) > 0){

                first = middle + 1;

            } else if (strcmp(name, pSRecord[middle]->LastNames) < 0){

                last = middle - 1;

            }
        }
    } else  if{

        printf("No Record Found With The Last Name %s. \n", name);
        exit(0);

    }

2 个答案:

答案 0 :(得分:0)

虽然这甚至不应该编译,因为(...} else if {...)

但忽略了这一点,为什么你有if(first&lt; = last)和while(first&lt; = last)?

while(first&lt; = last)只能正常工作

您的代码应该看起来像

while(first<= last){

        middle = (first + last)/2;

        if(strcmp(name, pSRecord[middle]->LastNames) == 0){

            printf("The Following Record Was Found: \nName: %s %s \nStudent ID: %d \nStudent Grade: %d \n", pSRecord[middle]->FirstNames, pSRecord[middle]->LastNames, pSRecord[middle]->IDNums, pSRecord[middle]->Marks);
            exit(0);

        } else if (strcmp(name, pSRecord[middle]->LastNames) > 0){

            first = middle + 1;

        } else if (strcmp(name, pSRecord[middle]->LastNames) < 0){

            last = middle - 1;

        }
    }

将它放在一个函数中,如果它存在则返回它的索引,如果不存在则返回-1,并且你已经完成了

答案 1 :(得分:0)

除了这种无效的构造

else  if{

外部if语句没有意义,因为变量firstlast在while循环中被更改。

只需删除它

    while(first<= last){

        middle = (first + last)/2;

        if(strcmp(name, pSRecord[middle]->LastNames) == 0){

            printf("The Following Record Was Found: \nName: %s %s \nStudent ID: %d \nStudent Grade: %d \n", pSRecord[middle]->FirstNames, pSRecord[middle]->LastNames, pSRecord[middle]->IDNums, pSRecord[middle]->Marks);
            exit(0);

        } else if (strcmp(name, pSRecord[middle]->LastNames) > 0){

            first = middle + 1;

        } else if (strcmp(name, pSRecord[middle]->LastNames) < 0){

            last = middle - 1;

        }
    }

    printf("No Record Found With The Last Name %s. \n", name);
    exit(0);