栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++学习案例:猜数字游戏

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++学习案例:猜数字游戏

最近在学习C++,遇到了一个案例:猜数字游戏

案例要求:系统生成一个范围在1-100的随机整数,用户有5次猜数字的机会,当用户猜的数字大于或小于生成的值时进行提示,5次没猜对则失败,猜对则成功;
代码:

#include 
#include 
#include 
using namespace std;

int main(){
    int rand_num = rand()%(1 - 100);
    cout << "rand_num = " << rand_num << endl;
    int user_input;
    int gameTime = 0;
    int maxGameTime = 5;
    cout << "请输入一个1-100的数字:" << endl;
    cin >> user_input;
    while (gameTime < maxGameTime){
        if (user_input == rand_num){
            cout << "恭喜你猜对啦!" << endl;
            break;
        }
        else if (user_input < rand_num){
            gameTime ++;
            cout << "数字偏小了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl;
            cout << "请输入一个1-100的数字:" << endl;
            cin >> user_input;
        }
        else if (user_input > rand_num){
            gameTime ++;
            cout << "数字偏大了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl;
            cout << "请输入一个1-100的数字:" << endl;
            cin >> user_input;
        }
    }
    return 0;
}

第一次运行是可以的,但是反复运行后,发现每次生成的随机数都一样的,查了一下资料:

rand()函数生成随机数需要通过srand()函数设置一个随机数种子。srand()和rand()配合使用产生伪随机数序列。rand函数在产生随机数前,需要系统提供的生成伪随机数序列的种子
rand()根据这个种子的值产生一系列随机数。如果系统提供的种子没有变化,每次调用rand函数生成的伪随机数序列都是一样的。
srand(unsignedseed)通过参数seed改变系统提供的种子值,从而可以使得每次调用rand函数生成的伪随机数序列不同,从而实现真正意义上的“随机”。
通常可以利用系统时间来改变系统的种子值,即srand(time(NULL)),可以为rand函数提供不同的种子值,进而产生不同的随机数序列。

原来在C++中,需要生成随机种子去改变随机数序列,好,上代码:

#include 
#include 
#include 
using namespace std;

int main(){
    srand((unsigned)time(NULL));
    
    int rand_num = rand()%(1 - 100);
    cout << "rand_num = " << rand_num << endl;
    int user_input;
    int gameTime = 0;
    int maxGameTime = 5;
    cout << "请输入一个1-100的数字:" << endl;
    cin >> user_input;
    while (gameTime < maxGameTime){
        if (user_input == rand_num){
            cout << "恭喜你猜对啦!" << endl;
            break;
        }
        else if (user_input < rand_num){
            gameTime ++;
            cout << "数字偏小了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl;
            cout << "请输入一个1-100的数字:" << endl;
            cin >> user_input;
        }
        else if (user_input > rand_num){
            gameTime ++;
            cout << "数字偏大了哦,再想想?剩余次数:" << maxGameTime - gameTime << endl;
            cout << "请输入一个1-100的数字:" << endl;
            cin >> user_input;
        }
    }
    return 0;
}

搞定~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/718851.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号