C++中的rand函数与srand函数

rand函数
函数原型:int rand(void);
所需头文件:cstdlib
功能和返回值:求出并返回一个伪随机数

srand函数
函数原型:void srand(unsigned int seed);
参数:seed产生随机数的种子
所需头文件:cstdlib
功能:为使rand()产生一序列伪随机整数而设置起始点。使用1作为seed参数,可以重新初化rand()。

举例:投骰子的随机游戏
每个骰子有六面,点数分别为1、2、3、4、5、6。游戏者在程序开始时输入一个无符号整数,作为产生随机数的种子。

每轮投两次骰子,第一轮如果和数为7或11则为胜,游戏结束;和数为2、3或12则为负,游戏结束;和数为其它值则将此值作为自己的点数,继续第二轮、第三轮…直到某轮的和数等于点数则取胜,若在此前出现和数为7则为负。

代码实现

#include<iostream>
#include<cstdlib>
using namespace std;

enum GameStatus{WIN,LOSE,PLAYING};
int rollDice();

int main()
{
	int sum, myPoint;
	GameStatus status;
	unsigned seed;
	cout << "please enter an unsigned integer: ";
	cin >> seed;			//输入随机数种子
	srand(seed);			//将种子传递给rand()
	sum = rollDice();		//第一轮投骰子,计算和数

	switch (sum)
	{
	case 7:
	case 11:				//如果和数为7或11则胜
		status = WIN;
		break;
	case 2:
	case 3:
	case 12:				//和数为2/3/12为负
		status = LOSE;
		break;
	default:				//其他情况,暂无结果,状态为PLAYING,记下点数
		status = PLAYING;
		myPoint = sum;
		cout << "point is " << myPoint << endl;
		break;
	}

	while (status == PLAYING)		//只要状态为PLAYING,继续
	{
		sum = rollDice();
		if (sum == myPoint)		//某轮的和数等于点数则取胜
			status = WIN;
		else if (sum == 7)		//出现和数为7则负
			status = LOSE;
	}

	if (status == WIN)
		cout << "player wins" << endl;
	else
		cout << "player loses" << endl;

	return 0;
}

int rollDice()
{
	int die1 = 1 + rand() % 6;		//对6取余,余数为1到5,再加1,就是骰子数字
	int die2 = 1 + rand() % 6;
	int sum = die1 + die2;
	cout << "player rolled " << die1 << "+" << die2 << "=" << sum << endl;
	return sum;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值