gpt4 book ai didi

c++ - 二进制搜索 - 代码编译和运行后不显示输出

转载 作者:行者123 更新时间:2023-11-28 01:40:53 24 4
gpt4 key购买 nike

我刚刚在类里面学习二分查找,下面的代码只是一个示例,因为我正试图更好地理解它。所以话虽如此,这段代码正在编译但没有显示任何输出,并且由于我缺乏二进制搜索的知识,我不知道为什么没有任何输出。有人可以指出写得很好的教程的方向吗?或者帮助指出代码有什么问题。

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>

using namespace std;
int SIZE = 10;

int main()
{
int thisArray[] = { 99,86,44,55,78,63,0,32,11 };
int num = 0;

int n = 0;

int first;
int last;
int middle;
first = 0;
last = n - 1;
middle = (first + last) / 2;
cout << "Enter the total number of elements\n";
cin >> n;

cout << "Entered " << n << "number.\n";

for (int i = 0; i < n; i++) {
cin >> thisArray[i];
}

cout << "Enter a number to find.\n";
cin >> num;

while (first <= last) {
if (thisArray[middle] < num) {
first = middle + 1;
}
else if (thisArray[middle] == num ) {
cout << num << " found at location " << middle + 1 << "\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last) / 2;
}


return 0;
}

编辑:

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>

using namespace std;
int SIZE = 10;

int main()
{
//this is my binary search
int thisArray[10] = { 0,11,32,44,55,63,78,86,99 };
int i = 0; //index of the array
int n = 0; //variable of number that will be looked for
int first = 0;
int last = SIZE - 1;
int middle;
int pos = -1;
bool found = false;
int count = 0;
while (found) {

cout << "Enter a number to look for.\n";
cin >> n;


while (first <= last) {
middle = first + last / 2;
if (thisArray[middle] == n) {

pos = middle;
cout << "item found at " << middle + 1 << "\n";

exit(0);
}
else if (thisArray[middle] > n) {
last = middle - 1;
}
else {
first = middle + 1;
}//endif
}//end while
}//end big while
//if()


return 0;
}

我明白了。感谢大家的帮助!

最佳答案

它没有输出任何东西,因为 first == 0last == -1 .因此 first <= last永远不会为真,并且永远不会执行循环体。

关于c++ - 二进制搜索 - 代码编译和运行后不显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com