且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

菜鸟学C:猜数字

更新时间:2022-09-18 13:43:09

源代码:


  1.  1 #include <stdio.h>  
  2.  2 int main(void)  
  3.  3 {  
  4.  4         int max = 100;  
  5.  5         int min = 1;  
  6.  6         int guess = ( max + min ) / 2;  
  7.  7         char response;  
  8.  8         printf("%d,large, small or yes?Enter(l|s|y):",guess);  
  9.  9         while((response = getchar()) != 'y')  
  10. 10         {  
  11. 11                 if(response == 's')  
  12. 12                 {  
  13. 13                         max = guess;  
  14. 14                         guess = ( max + min ) / 2;  
  15. 15                 }  
  16. 16                 else if(response == 'l')  
  17. 17                 {  
  18. 18                         min = guess;  
  19. 19                         guess = ( max + min ) / 2;  
  20. 20                 }  
  21. 21                 else 
  22. 22                 {  
  23. 23                         printf("Input error!");  
  24. 24                 }  
  25. 25                 while(getchar() != '\n')  
  26. 26                         continue;  
  27. 27                 printf("%d,large, small or yes?Enter(l|s|y):",guess);  
  28. 28         }  
  29. 29         printf("Your guess number is %d\n",guess);  
  30. 30         return 0;  
  31. 31 } 

运行效果:

 :!gcc test5.c -o test5
:! ./test5
50,large, small or yes?Enter(l|s|y):l
75,large, small or yes?Enter(l|s|y):s
62,large, small or yes?Enter(l|s|y):l
68,large, small or yes?Enter(l|s|y):s
65,large, small or yes?Enter(l|s|y):l
66,large, small or yes?Enter(l|s|y):y

Your guess number is 66

本文转自运维笔记博客51CTO博客,原文链接http://blog.51cto.com/lihuipeng/760487如需转载请自行联系原作者


lihuipeng