+ 1
How do I randomise a variable within a certain number range?
e.g. 1 ~ 5 *Sets EnemyType to randomised number* if (EnemyType=1) { cout << "A goblin leaps out from behind a rock, knife at the ready" EnemyHP=4 EnemyDMG=1 } Sorry if I got some code wrong, I hope you understand the question.
3 Respostas
+ 4
first, within int main(), set the random seed:
srand(time(NULL)); //to do this, you'll need #include <cstdlib> and #include <time>
then you can make a function to return a random number from 1 to N. I like to use this one:
int rand0toN(int n) {
return (rand() % n) + 1;
}
then you can call it like this:
int enemyType = rand0toN(5);
hope this solves it! Also, the answer below (KG) will give you a random number 0 to 4, not 1 to 5
0
srand (time(NULL))
num=srand() %5
0
To give random variable for range 1-5 simply put
a=random(5)+1;
'a' can be random variable
(as random of 5 will generate number from 0-4 so we are adding 1)