C++猜数字。

本文介绍了使用C++编写的猜数字游戏,包括计算机猜测和玩家猜测两个模式,通过二分查找算法让玩家在15次内猜测1到10000之间的数字。
摘要由CSDN通过智能技术生成

#include<bits/stdc++.h>
using namespace std;
void _computer_guess();
void _player_guess();
void _computer_guess() {
    short int smaller=1,biger=10000,time=1,pn;
    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<<"1.Biger 2.Smaller 3.Right    Please in:(1 or 2 or 3)"<<endl;
        cin>>pn;
        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() {
    short int cn=rand()%10000+1,pn,time=1;
    cout<<"I will think about a number in 1 to 10000. Can you use 15 times to guess right it?"<<endl;
    while(time<=15) {
        cout<<time<<". You think my number is : ";
        cin>>pn;
        if (pn<cn)cout<<pn<<" is smaller than my number."<<endl;
        if (pn>cn)cout<<pn<<" is biger than my number."<<endl;
        if (pn==cn)cout<<pn<<" is my number."<<endl<<" You win!"<<endl;
        break;
        if (time>15)break;
        time+=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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值