CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Threaded View

  1. #3
    Join Date
    May 2009
    Posts
    2,413

    Re: Random Number Generator Problems

    Quote Originally Posted by Herpestidae View Post
    What am I doing wrong?
    You have to be more careful with boundaries.

    This will give you 7 random numbers (between 0 and 6) and not 8 as you probably want,
    Code:
        int r= rand();
        int s= r%7;
    And this will loop 9 times giving indexes between 0 and 8 (of which the last will fall outside the 8 element array),
    Code:
        for(int i=0; i<=8; i++)
    Then the problem with the random numbers. You call srand(parameter) to select a random sequence. Each parameter is associated with one random sequence. It's usually enought to do this only once in a program. So move
    Code:
            srand(time(NULL));
    to the beginning of the program or at least outside the loop where it now resides.

    In principle you could keep it where it sits now if you changed the call to srand(i). Then rand() would return a different random number in each iteration of the loop. But this would be the first random number of a different random sequence and that would be unfortunate for two reasons. First you have no guarantee that the random numbers so selected will be independent (and this means you unwittingly degrade the quality or the random generator). And second the numbers will be the same in each run of the program (which you obviously don't want since you seed from the system timer).

    Still the question of why you always get the same random numbers hasn't been answered. It's because of the resolution of time(). It only ticks/changes once a millisecond or so. This means when it's called several times in quick succession it will return the same time. And this means srand() is seeded with the same parameter and rand() will always return the first random number of the same random sequence.
    Last edited by nuzzle; September 29th, 2012 at 10:53 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured