[C语言][小游戏]输入一个数让电脑来猜你输入的数

直接上代码

#include <stdio.h>          //用来控制输入输出
#include <time.h>           //用来初始化随机数种子
#include <stdlib.h>         //用来调用rand随机数函数
#define M 1000000000        //最大值
int main()
{
    
    
    int left = 0,right = M;
    int mid;
    int answer;
    int count = 0;
    srand((unsigned int)time(0)); 
    printf("请输入数字让电脑来猜(1-%d):",M);
    scanf("%d",&answer);
    mid = (left + right) / 2;
    while(mid != answer)
    {
    
    
        count++;
        printf("此时letf=%10d,right=%10d ",left,right);
        if(mid > answer)
        {
    
    
            printf("电脑第 %2d 次输入的 %9d 比答案 大\n",count,mid);
            right = mid - 1;
        }
        else
        {
    
    
            printf("电脑第 %2d 次输入的 %9d 比答案 小\n",count,mid);
            left = mid + 1;
        }
        mid = (left + right) / 2;
    }
    printf("恭喜第 %2d 次终于猜中答案啦,答案就是%9d吧\n",count,answer);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_28406527/article/details/121570668