程序「隨機」選擇一組8個數字,然後用戶必須儘可能多地猜出這些數字。但即使我輸入這個隨機數組中的數字,binary_search函數也不會在'random'數組中找到確切的數字。我似乎無法找到我的binary_search函數中的錯誤(至少我懷疑這是問題所在)。我已經嘗試過大號和小號的程序。任何人都可以幫助我嗎?C中的二進制搜索功能
#define SIZE 3
#define min 1
#define max 36
int random();
bool binary_search(int value, int values[], int n);
int main(void)
{
int numbers[SIZE];
for(int i = 0; i < SIZE; i++)
numbers[i] = random();
int score = 0;
int n[SIZE];
int number_user;
for(int i = 0; i < SIZE; i++)
{
//Type in a number
do
{
printf("Search number no.%d:\n> ", i + 1);
n[i] = GetInt();
//Wrong input number
if(n[i] < min || n[i] > max)
{
printf("\nNumber should be between %d - %d!!!\n\n", min , max);
}
}
while(n[i] < min || n[i] > max);
//THE PROBLEMATIC STUFF - START
number_user = n[i];
if (binary_search(number_user, numbers, SIZE))
{
printf("FOUND!!!\n");
score += 1;
}
else
{
printf("NOT IN THE LIST\n");
}
//PROBLEMATIC STUFF - FINISH
}
//scoring
printf("\n\n*******SCORE*******\n");
//print your numbers
for(int i = 0; i < SIZE; i++)
{
printf(" %d", n[i]);
if(i != SIZE - 1)
printf(",");
if(i == SIZE - 1)
printf(".\n");
}
//print right numbers
printf("\nRight numbers are:");
for(int i = 0; i < SIZE; i++)
{
printf(" %d", numbers[i]);
if(i != SIZE - 1)
printf(",");
if(i == SIZE - 1)
printf(".\n");
}
int result = score/SIZE * 100;
printf("Your score is: %d/%d , %d %%\n", score, SIZE, result);
return 0;
}
//PROBLEM START
bool binary_search(int value, int values[], int n)
{
int beginning = 0;
int ending = n - 1;
int middle;
while (ending >= beginning)
{
middle = (beginning + ending)/2;
for(int i = 0; i < SIZE; i++)
{
//look at middle of list if (binary_search(n, numbers, SIZE))
if(values[middle] == value)
//if number found, return true
return true;
//else if middle higher, search left
else if(values[middle] > value)
ending = middle - 1;
//else if middle lower, search right
else if(values[middle] < value)
beginning = middle + 1;
}
}
return false;
}
//PROBLEM FINISH
int random()
{
int r = rand() % ((max - min + 1) + min);
return r;
}
二進制搜索中的for循環有什麼意義? – kviiri
我認爲有必要先排序以搜索數字。 – BLUEPIXY
不,它真的不是... – kviiri