-3

This is my function:

Random(int min, int max)
{
    srand(time(NULL));
    return (rand() % (max-min)) + 1;
    // or
    return (rand() % (max+min)) + 1;
    // or
    return (rand() % (max-min))
    // or
    return (rand() % (max+min))
};

And it isn't working, if I say add Random(5, 10) it sometimes show up 15, 5, 4. I can't figure it out, because all guides say "this is the way it's suppose to be" but it doesn't work. What have I missed?

This methos is part of a class.

I've tried srand(time(NULL)) placed in:

  1. Not at all
  2. In constructor
  3. In method

No results.

Shouldn't rand() return a value between 0 and 1? Mine doesn't.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Deukalion
  • 2,516
  • 9
  • 32
  • 50
  • 1
    You should "figure out" how functions work by reading the documentation and *thinking* about the code you write, instead of trying every permutation of the relevant tokens in your code. – Matteo Italia Jun 22 '12 at 10:23
  • Related, please read. http://stackoverflow.com/a/686373/241536 – John Dibling Jun 22 '12 at 13:19

2 Answers2

7
  1. Call srand only once
  2. Use return (rand() % (max-min+1)) + min; (+1 is for including max into range)
  3. rand() returns a value between 0 and RAND_MAX and is a positive integer.
Lyth
  • 2,171
  • 2
  • 29
  • 37
  • 1
    @Deukalion: You can learn all of this and much more from the fine documentation, e.g. the [manual page of `rand`](http://linux.die.net/man/3/rand) in section 3. – thiton Jun 22 '12 at 10:21
  • Thank you. I tried every example and it didn't work at all. I have been using these functions since forever, never tried understanding enough but I understand the principle. And I just forgot about minimum. Sorry, about this mess :P – Deukalion Jun 22 '12 at 10:29
3

man rand(3)

function signature is int rand(void); So it already can't return a value between 0 and 1 since its an integral.

Return values: The rand() and rand_r() functions return a value between 0 and RAND_MAX (inclusive). The srand() function returns no value.

from man rand(3)

RedX
  • 14,749
  • 1
  • 53
  • 76