Bevilacqua
Bevilacqua

Reputation: 475

Random Number Generation using srand() defining a variable

Here is the code that doesn't work:

Enemy.strength = srand((unsigned)time(NULL)) % 10;

Enemy.strength is an int

I did some research and i found you can't directly define a variable with rand/srand such as:

a = rand();

I am just wondering why and if there is a way around this or what alternative you suggest

Language: C... not C++

Upvotes: 0

Views: 3093

Answers (3)

Naga Venkatesh
Naga Venkatesh

Reputation: 99

Please refer the below links for further understanding
srand
rand

Upvotes: 0

Michael Anthony
Michael Anthony

Reputation: 85

srand() accepts the seed as its first argument. Simply place the call to srand() before you assign Enemy.strength and assign the return value of rand() to it instead.

Example

srand((unsigned)time(NULL)), Enemy.strength = rand() % 10;

Upvotes: 1

sjs
sjs

Reputation: 9330

srand(seed) returns void. It is for seeding the random number generator. rand() returns a pseudo-random integer between 0 and RAND_MAX (defined in stdlib.h).

So to get a random strength for your enemy you should do something like:

Enemy.strength = rand() % 10; // gives a strength between 0 and 9

You can place a call to srand somewhere in your code, but it only needs to be called once. It should be called before any calls to rand().

Upvotes: 4

Related Questions