+ 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.

22nd Oct 2016, 12:41 AM
miningpieeater
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
24th Oct 2016, 2:09 AM
Zeke Williams
Zeke Williams - avatar
0
srand (time(NULL)) num=srand() %5
22nd Oct 2016, 1:10 AM
KG Feignh
KG Feignh - avatar
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)
22nd Oct 2016, 9:03 AM
Mayank Garg
Mayank Garg - avatar