rand函数的简单使用

rand函数的简单使用
#include <iostream>
#include <cstdlib>

using namespace std;

/****剪刀石头布游戏****/
int main()
{
    int user=0;
    int pc=0;
    cout<<"****这是一个剪刀石头布游戏*****"<<endl;
    cout<<"0:石头    1:剪刀     2:布"<<endl;
    for(;;)
    {
        /*这里注意***:
         *
         *  1.rand()函数用到了随机数种子,一旦分配后,种子的值不变。
         *  所以我们要可以把它放在循环里,重复该语句就会得到不同的
         *  种子的值。
         *  2.如果不用循环,可以采用srand()函数来产生随机数,用法如下:
         *     srand(time(NULL));      //#include <time.h>
         *     pc=rand()%3;
         *
         */
        pc=rand()%3;
        cout<<endl;
        cout<<"请输入你要摆出的选项:";
        cin>>user;
        cout<<endl;
        if(user>2||user<0)
        {
            for(;;)
            {
                cout<<"输入有误,请重新输入:";
                cin>>user;
                cout<<endl;
                if(user<=2&&user>=0)
                {
                    break;
                }
            }
        }
        cout<<"玩家摆出:"<<user<<'\t'<<"电脑摆出:"<<pc<<endl;
        if(user==pc)
        {
            cout<<"平局!"<<endl;
        }
        else
        {
            if((user+1)%3==pc)
            {
                cout<<"玩家获胜!!"<<endl;
            }
            else
            {
                cout<<"电脑获胜!!"<<endl;
            }
        }
    }
    return 0;
}
//玩家(赢)      电脑(输)
//0                           1
//1                           2
//2                           0
//(user+1)%3==pc

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值