分享一个二分法程序,望大佬指教有无简化方法,谢谢!
#include <stdio.h>#define M 10
int main()
{
int n,low,high,found,mid,a = {1,2,3,4,5,6,7,8,9,10};
low = 0;high = M-1;found = 0;
printf("Please input the search number: ");
scanf("%d",&n);
while(low <= high)
{
mid = (low + high)/2;
if(a == n)
{
found = 1;
break;
}
else
{
if(a > n)
{
high = mid-1;
}
else
{
low = mid+1;
}
}
}
if(found == 1)
{
printf("The number is:%d\n",a);
}
else
{
printf("The number is not search!!!");
}
return 0;
} 本帖最后由 jackz007 于 2019-10-28 14:37 编辑
#include <stdio.h>
#define M 10
int main()
{
int n , low , high , found , mid , a = {1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10} ;
low = 0 ;
high = M - 1 ;
found = 0 ;
do {
printf("Please input the search number: ") ;
scanf("%d" , & n) ;
} while(n < a || n > a) ;
while(low <= high) {
mid = (low + high) / 2 ;
if (n == a) {
found = 1 ;
break ;
} else {
if (n > a) low = mid + 1 ;
else high = mid - 1 ;
}
}
if(found) printf("The number is:%d\n" , a) ;
else printf("The number is not search!!!") ;
}
页:
[1]