我的二进制搜索只返回数字不能是C



这里的初学者,我无法修复错误,因为我不知道该怎么做了,也不知道代码出了什么问题。每个输入都返回它显示的";该数字不是数组"的一部分;不管数字是多少。我使用了100个随机数字,范围从0到900,作为我的列表,这些数字已经排序。如果有人能在这方面帮助我,我将不胜感激。

void find(int * randomized, int size, int * menu) {
if((*menu)>=2){
printf("nEnter the number you are searching for: ");
char tal[SIZE];
fgets(tal, LENGTH, stdin);
strtok(tal, "n");
int choice=atoi(tal);
int high=size-1;
int mid;
int low = 0;
int remainder, split;
while (low<=high){
mid = (low+high)/2;
if(randomized[mid]==choice){
remainder=(mid+1) %10;
split=(mid+1) /10;
if(remainder == 0 && split == 10){
remainder=10;
split=10;
}
else if( remainder == 1 && split == 0){
remainder=1;
split=1;
}
else if(remainder == 0 && split >0 && split <10){
remainder=10;
split=10;
}
else{
split=(mid+1)%10;
}
printf("n The numer %d is a part of the array.nColumn: %dn Line: %d", choice, remainder, split);
return;

}
else if(randomized[mid] !=choice){
printf("nThe number %d is not part of the array.n", choice);
return;
}
else if (randomized[mid] <choice){
low=mid+1;
}
else{
high = mid - 1;
}
}
(*menu=4);
}

代码有一个if,后面跟着三个else测试。由于第一个测试用于不等式,第二个测试用于不等式,因此永远无法输入最后两个else代码块。

if(randomized[mid]==choice){
// some code ...
}
else if(randomized[mid] !=choice){
// some code ...
}
else if (randomized[mid] <choice){
// some code ...
}
else{
// some code ...
}

由于二进制搜索中塞满了太多的功能,代码变得很难理解。它应该专注于一项工作,并给出一个正确或错误的结果,然后你就可以采取行动了

最新更新