C++猜数字游戏

要求:

1.生成一个随机数作为答案。
2.要求用户输入猜测的数字。
3.断用户猜测的数字是否与答案相同,如果不同则给出相应的提示信息,如“猜大了”、“猜小了”等。
4.循环进行猜测和提示,直到用户猜中为止。
5.可以设置猜测次数上限,超过上限未猜中则游戏失败。

代码:

#include <iostream>
#include<cstdlib>   //包含rand()函数
#include<ctime>     //包含time()函数
using namespace std;

int main()
{
    cout << "猜数字:" << endl;
    int num,max,min,m,n=0;    //猜测值,最大值,最小值,猜测次数上限,猜测次数
    cout << endl << "请输入随机数的最小值:";
    cin >> min;
    cout << endl << "请输入随机数的最大值:";
    cin >> max;
    cout << endl << "请输入需要猜测的次数:";
    cin >> m;
    //生成随机数
    srand(time(nullptr));   //设定种子
    int random_number = rand() % (max - min + 1) + min;    //生成随机数并限定范围为min-max;
    while (true)
    {
        ++n;
        cout <<endl << "请输入猜测的数字:";
        cin >> num;
        if (num == random_number) {
            cout << "猜对了!" << endl;
            break;
        } 
        else
        {
            cout << "猜错了!" << endl;
            if (num < random_number) cout << endl << "它比" << num << "要大";
            else cout<< endl << "它比" << num << "要小";
        }
        if (n == m) {
            cout <<endl << "游戏失败!";
            break;
        }    
    }
    cout <<endl << "随机数为:" << random_number << endl;
    system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值