基本上,我需要找出如何在屏幕上输出值,以实现二进制搜索的成功部分。我试图更改的初始值,last
但它要么崩溃,要么保持不变。我逐步浏览了代码,一切似乎都正常。
来自编译器的程序示例
#include<iostream>
using namespace std;
void binarySearch();
int main()
{
//Called the function in main
binarySearch();
system("pause");
return 0;
};
//void function for binary Search
void binarySearch()
{
//creating array
int array[100];
array[0] = 1;
int i,target;
// using Boolean to create pattern for generated numbers in the array
bool check = false;
//loop to implement pattern
for (int x = 1; x < 100; x++)
{
if (check == true)
{
array[x] = array[x - 1] + 1;
check = false;
}
else
{
array[x] = array[x - 1] + 2;
check = true;
}
}
**Code found online and modified to fit**
int first,mid,last,completed,successful,tests;
completed = 0;
successful = 0;
tests = 0;
double percentage;
percentage = 1;
for(int x=0;x<100;x++)
{
// Initialize first and last variables.
first = 0;
last = 2;
srand( (unsigned)time( NULL ) );
int target = (rand() % 150) + 1;
while(first <= last)
{
mid = (first + last)/2;
if(target > array[mid])
{
first = mid + 1;
tests++;
}
else if(target < array[mid])
{
last = mid + 1;
tests++;
}
else
{
first = last - 1;
}
if(target == array[mid])
{
successful++;
}
}
completed++;
}
**Area which the error occur No value for successful**
//Output on screen
cout << endl;
cout << "There were "<< completed <<" searches completed."<< endl;
cout << "There were "<< successful <<" successful searches." << endl;
cout << percentage <<"%"<<" of the searches were successful." << endl;
cout << "There was an average of " << completed << " tests per search." << endl;
cout << endl;
}