简体   繁体   English

C ++二进制搜索斗争

[英]C++ binary search struggle

Sorry for using polish names but I started with them and didin't want to confuse myself. 很抱歉使用波兰名字,但我从他们开始,并不想混淆自己。 I've got an assignment to find the possible answer to this equation x^3 + px = q , without negative numbers. 我有一个任务,找到这个方程的可能答案x^3 + px = q ,没有负数。 Also I Have to use binary searching for that, it seemed to me pretty easy at first but I keep on getting wrong outputs. 此外,我必须使用二进制搜索,一开始我觉得很容易,但我继续得错输出。 Just wanted some advice on what I should focus on, not an entire solution. 只是想要一些关于我应该关注的建议,而不是整个解决方案。 Cheers! 干杯!

int main() {
int p, q, x;
cin >> p >> q;
int tablica[q-1];
for(int i = q-1; i>=0; i--){
    tablica[i] = q;
    q--;
}
bool znalezione = false;
int poczatek = 0;
int koniec = q-1;


while(!znalezione){
    int srodek = (poczatek + koniec)/2;
    tablica[srodek] = x;
    if(x*x*x + p*x == q){
        znalezione = true;
    }
    else
        if(x*x*x + p*x > q){
            koniec = srodek -1;
        }
        else
            poczatek = srodek +1;
}
cout << x;

} }

You are trying to find the value of x . 您正试图找到x的值。 The first thing that I notice is that x is not initialized and then in the line tablica[srodek] = x , you are assigning this to array, this will give a garbage value in tablica . 我注意到的第一件事是x没有被初始化,然后在行tablica[srodek] = x ,你将它分配给数组,这将在tablica给出一个垃圾值。

Additionally, you are never updating the value of x . 此外,您永远不会更新x的值。 It will always display the value which was at the beginning (garbage value in your case) 它将始终显示开头的值(在您的情况下为垃圾值)

int tablica[q-1]; is not standard c++, use std::vector . 不是标准的c ++,使用std::vector I'm not sure why you even need a table. 我不确定你为什么甚至需要一张桌子。 You've got the general idea but you never assigned anything to x . 你有一般的想法,但你从来没有给x分配任何东西。 Binary search algorithm is something like this: 二进制搜索算法是这样的:

std::optional<int> binary_search(int begin, int end, int element)
{
    while(end-begin>0)
    {
        int midPoint = (end+begin)/2;
        if(midPoint ==element)
            return midPoint;
        else if (midPoint > element)
            begin = midPoint+1;
        else
            end = midPoint-1;
    }
    return {};
}

So all you have to do is replace insides of those if statements with your equation. 因此,您所要做的就是用等式替换那些if语句的内部。

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

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