简体   繁体   English

为什么我的编译器 go 在 C++(二进制搜索)的无限循环中?

[英]Why does my compiler go in an infinite loop with c++(binary search)?

When I try to run my code, the terminal outputs a compiler line and than goes blank.当我尝试运行我的代码时,终端输出一个编译器行,然后变为空白。 Why does my terminal go blank?为什么我的终端 go 空白? And why is it in an infinite loop?为什么它处于无限循环中?

Here is the code:这是代码:

#include <iostream>

using namespace std;

int biSearch(int list[] ,int lenght,int t);

int main() 
{

    int nums[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int func_return = biSearch(nums,10,7);
    cout << func_return << endl;

    if(func_return != -1)
    {
        cout << "index: " << func_return << endl;
    }

    else
    {
        cout << "not found" << endl;
    }

}

int biSearch(int list[],int lenght,int t) 
{
    int f = 0;
    int l = lenght - 1;
    int m = (l - f) / 2;


    while(f<=l)
    {
        if (list[m] == t)
        {
            return m;
        }

        else
        {
            if (t < list[m])
            {
                l = m - 1;
                m = (l - f) / 2;
            }

            else
            {
                f = m + 1;
                m = (l - f) / 2;
            }
        }
    }

    
    return -1;
}

The output of the terminal before it breaks:断线前终端的output:

Copyright (C) Microsoft Corporation. Todos os direitos reservados.

Experimente a nova plataforma cruzada PowerShell https://aka.ms/pscore6

PS D:\Docs\CodeProjects\Nova pasta> cd "d:\Docs\CodeProjects\Nova pasta\" ; if ($?) { g++ hw.cpp -o hw } ; if ($?) { .\hw }

After this output, the terminal just prints a singular blank line.. Why does my compiler go in an infinite loop?在这个 output 之后,终端只打印一个奇异的空行。为什么我的编译器 go 在无限循环中?

Here's your real bug:这是你真正的错误:

int m = (l - f) / 2;

Ask yourself this.问问自己这个。 Does (lf)/2 accurately compute the midpoint index between l and f ? (lf)/2是否准确计算lf之间的中点索引? Let me know if you don't figure it out and I'll give another hint.如果你不明白,请告诉我,我会给出另一个提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM