二分查找猜数小玩具

 1 #include <stdio.h>
 2 int step=1;
 3 void cut2_1(int w,int x,int y)
 4 {
 5     int m=x+(y-x)/2;
 6 //    printf("num:%d to %d\n",x,y);
 7     if(w!=m)
 8     {
 9         printf("step%d,%d? %s\n",step++,m,m>w?"too big":"too small");
10         if(m>w)
11             cut2_1(w,x,m-1);
12         else 
13             cut2_1(w,m+1,y);
14     }
15     else printf("step%d,%d?\nAnswer is %d,you r right!",step,m,w);
16 }
17 void cut2_2(int w,int x,int y)
18 {
19     int m=x+(y-x)/2;
20     while(m!=w)
21     {
22         printf("step%d,%d? %s\n",step++,m,m>w?"too big":"too small");
23         m>w?y=m-1:x=m+1;
24         m=x+(y-x)/2;
25     }
26     printf("step%d,%d?\nAnswer is %d,you r right!",step,m,w);
27 }
28 int main()
29 {
30     int ans;
31     int sum=10000;
32     scanf("%d",&ans);
33     cut2_2(ans,1,sum);
34     return 0;
35 }

 

posted on 2015-08-05 10:35  Ricochet!  阅读(205)  评论(0编辑  收藏  举报