Cody Richardson
Cody Richardson

Reputation: 157

Randomizer Not working properly

I made a little randomizer and it's not working correctly. Here's the code...

I have a function,

short rnd(short *num){
    return (rand() % max) + 1;
}

which has a prototype of

short rnd(short *num);

When I use this, I do something like this:

max = 10;
num = rnd(&max);

the compiler throws no problems, but it is always equal to 0... Any suggestions?

Upvotes: 0

Views: 103

Answers (2)

John
John

Reputation: 2425

It appears that your max is a global variable. I would recommend passing it to your rnd function as a parameter rather than making it global, and if it doesn't change at runtime just create a macro for your max and pass that in.

short rnd(unsigned short max)
{
  return (rand() % max) + 1;
}

Upvotes: 4

Andrew B.
Andrew B.

Reputation: 167

In order to have a true random number it needs to be seeded. The best way to seed it is to use the time of the computer with srand() that is in the standard library.

#include <stdlib.h>
#include <time.h>
srand(time(NULL)); /*this in the main function*/

short rndnum(short max)
{
    return (short) (rand() % max) + 1;
}

this should produce random numbers between 1 and 10.

Upvotes: 0

Related Questions