dice.h

来自「为大家搜集免费的计算机学习、编程资料和优秀的网络资源。多多支持」· C头文件 代码 · 共 63 行

H
63
字号
#include <cstdlib>
#include <time.h>

// helper function used to initialize the random number generator
// by using an function external to the class, we ensure that the static variable it
// uses to track whether srand has been yet or not, is never in an undefined state
void InitializeRandomizer();

class Dice
{
private:
	// by making this private it prevents the use of a constructor with no parameters
	Dice();
	int value;
	int lower;
	int upper;

public:
	// will generate a random number between 1 and upper
	Dice(const int& iUpper)
	{
		lower=(iUpper==1 ? 0 : 1);
		upper=iUpper;
		InitializeRandomizer();
		value = (static_cast<int>(rand()%upper)) + lower;
	}
	
	// will generate a random number between lower and upper
	Dice(const int& iLower, const int& iUpper)
	{
		lower=(iLower==iUpper ? (iLower-1) : iLower);
		upper=iUpper;
		InitializeRandomizer();
		value = static_cast<int>(rand()%(upper-lower+1)) + lower;
	}

	int roll()
	{
		value = static_cast<int>(rand()%(upper-lower+1)) + lower;

		return value;
	}

	// generate n rolls of the same range
	int multi(const unsigned int& n)
	{
		value = 0;
		for(unsigned int i=0; i < n; ++i)
		{
			value += static_cast<int>(rand()%(upper-lower+1)) + lower;
		}

		return value;
	}

	// allows objects of the class to be treated as if they were ints, which in the case
	// of this class makes alot of sense
	operator int() const
	{
		return value;
	}
};

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?