C++猜数字。无bug。

本文介绍了使用C++编写的交互式猜数游戏,包含电脑采用二分查找算法猜测玩家选定的数字和玩家尝试在15次内猜中电脑所想的数字。
摘要由CSDN通过智能技术生成

#include<bits/stdc++.h>        //猜数主体部分。

#include <cstdlib>        //产生随机数

#include <ctime>        //产生随机数

using namespace std;

void _computer_guess();        //电脑猜数

void _player_guess();        //玩家猜数

void _computer_guess() {        //二分猜数法

    short int smaller=1,biger=10000,time=1,pn;        //time作为计数器
    
    cout<<"Please think about a number in 1 to 10000. I can guess it in 15 times."<<endl;
    
    while(time<=15&&smaller<=biger) {
        
        cout<<time<<". I think your numeber is :"<<(biger+1)/2<<endl<<"The number is 1.Biger 2.Smaller 3.Right    Please in:(1 or 2 or 3)"<<endl;
        
        cin>>pn;
        
        cout<<endl<<endl;
        
        if(pn==1)biger=(biger+smaller)/2;
        
        if(pn==2)smaller=(biger+smaller)/2;
        
        if(pn==3){cout<<"I win!"<<endl;break;}        //胜利
        
        time+=1;
        
    }
    
    cout<<"My time(s): "<<time<<endl;
    
}

void _player_guess() {
    
    srand((int)time(0));         //产生随机数种子
    
    short int cn=rand()%10000+1,pn,time=1;        //time作为计数器
    
    cout<<"I will think about a number in 1 to 10000. Can you use 15 times to guess right it?"<<endl;
    
    while(1) {
        
        cout<<time<<". You think my number is : ";
        
        cin>>pn;
        
        if (pn<cn)cout<<pn<<" is smaller than my number."<<endl<<endl;
        
        if (pn>cn)cout<<pn<<" is biger than my number."<<endl<<endl;
        
        if (pn==cn){cout<<pn<<" is my number."<<endl<<" You win!"<<endl<<endl;break;}        //胜利
        
        if (time>=15){cout<<"You lose!"<<endl<<"My number is : "<<cn<<endl<<endl;break;}        //次数超过15,停止计数
        
        time+=1;        //次数+1
        
    }
    
    cout<<"Your time(s): "<<time<<endl;
    
}

int main() {
    
    int number;        //玩家选择游戏方式
    
    while(1) {        //选择游戏(初始界面)
    
        cout<<"GUESS NUMBER GAME"<<endl; 
        
        cout<<"1.I guess your number"<<endl<<"2.You guess my number"<<endl<<"Please in:";
        
        cin>>number;
        
        system("cls");
        
        if(number==1)_computer_guess();
        
        if(number==2)_player_guess();
        
        system("pause");
        
        system("cls");
    }
    
    return 0;
    
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值