(C语言)二分算法实现简单猜数

本文介绍了一个简单的猜数字游戏程序,使用C语言编写。程序通过不断猜测用户心中选定的一个1到100之间的数字,并根据用户的反馈调整猜测范围,直至猜中为止。文中详细展示了程序的代码结构及核心算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1None.gif#include <stdio.h>
 2None.gifint guessnum(int,int);
 3None.gifchar correntchar(void);
 4None.gifint main(void)
 5ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 6InBlock.gif    char ch;
 7InBlock.gif    int min=1;int max=100;
 8InBlock.gif    int value;
 9InBlock.gif    printf("Pick a integer form 1 to 100,then I will try to guess it:");
10InBlock.gif    printf("\nSome answers you can choose to help me,as follows:");
11InBlock.gif    printf("\nb bigger than my answer    s smaller");
12InBlock.gif    printf("\ny corrent.");
13InBlock.gif    value=guessnum(min,max);
14InBlock.gif    printf("\nIs it %d?",value);
15InBlock.gif
16InBlock.gif    while((ch=correntchar())!='y')
17ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
18InBlock.gif            //while(getchar())
19InBlock.gif                if(ch=='b')
20InBlock.gif                    min=value;
21InBlock.gif                else if(ch=='s')
22InBlock.gif                    max=value;
23InBlock.gif                value=guessnum(min,max);
24InBlock.gif                printf("\nIs it %d?",value);
25ExpandedSubBlockEnd.gif        }

26InBlock.gif    printf("Oh,year!");
27InBlock.gif    return 0;
28ExpandedBlockEnd.gif}

29None.gifint guessnum(int min,int max)
30ExpandedBlockStart.gifContractedBlock.gifdot.gif{
31InBlock.gif    return (max+min)/2;
32ExpandedBlockEnd.gif}

33None.gifchar correntchar()
34ExpandedBlockStart.gifContractedBlock.gifdot.gif{
35InBlock.gif    char ch;
36InBlock.gif    ch=getchar();
37InBlock.gif    while(getchar()!='\n')
38InBlock.gif        continue;
39InBlock.gif    return ch;
40ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/feiren1421/archive/2006/02/26/337881.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值