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

    Find my mistake with the random command

    I'm writing a little routine that simulates the rolling of dice,
    but it gives the same numbers in the same order every time
    I run it, even if I recompile the code each time.

    My random routine looks like
    randomize();
    roll=random(sides)+1;

    I'm using Turbo C 4.5. Can you see any problem with the above?
    I have stdlib.h and time.h included...

    Thanks,
    Jason F.
    [email protected]


  2. #2
    Join Date
    May 1999
    Posts
    6

    Re: Find my mistake with the random command

    Hi Jason,

    I don't see what you are doing wrong but you could try this:
    ----
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>

    srand( (unsigned)time( NULL ) ); // is the same as randomize()
    roll = rand()%sides + 1 // is the same as random()
    ---
    randomize() and random() are not standard C !!
    maybe in Borland, but not in Microsoft C,
    so I advice you to use rand() and srand() like used above

    Good Luck,

    Rick Blommers
    [email protected]



  3. #3
    Guest

    Re: Find my mistake with the random command

    Try this (it will make your output look like dice too!):

    #include <iostream.h>
    #include <stdlib.h>
    #include <time.h>

    const int SIZE = 6;

    int main()
    {
    int one, two, total;
    srand(time(NULL));
    char *DieA[SIZE] = {".", ":", ":.", "::", ":.:", ":::"};
    char *DieB[SIZE] = {".", ":", ":.", "::", ":.:", ":::"};
    one = rand()%6 + 1;
    two = rand()%6 + 1;
    total = one + two;
    cout << "Die A is " << DieA[one-1] << endl;
    cout << "Die B is " << DieB[two-1] << endl;
    cout << "Total rolled was: " << total << "\n\n";
    return 0;
    }


  4. #4
    Join Date
    May 1999
    Posts
    28

    Re: Find my mistake with the random command

    I'm not exactly sure how "randomize" works in Turbo C, but the usual problem with random numbers is the seed of the random number generator. Randomizing functions are really just an equation that operates on a number. If you start with the same number every time, your "random" numbers will become predictable for as many as you can remember. Try seeding the random number with an internal time function such as seconds since 1980 or something.

    Chris R. Wheeler, MCP
    Pensacola Christian College
    Desktop Programmer
    [email protected]

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