random

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kasya
    New Member
    • Jun 2006
    • 57

    random

    How Can I random two digits?????

    Please help me!!!!!!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    I think you have some words missing from that question :D

    However the C standard library provides 2 routines for getting random values

    srand - this seeds the random number generator, often called as

    srand(time(NULL ));

    rand - this returns a value bwteen 0 and RAND_MAX, you will need to scale the return value to the range you require.

    Comment

    • Kasya
      New Member
      • Jun 2006
      • 57

      #3
      But I need only two digits for example:

      sometimes it shows 35 and sometimes it shows 45

      Comment

      • D_C
        Contributor
        • Jun 2006
        • 293

        #4
        Then make the range from 00 to 99, i.e. multiply the random value by 100, or take it modulo 100, depending on the range of the random value.

        Comment

        • Kasya
          New Member
          • Jun 2006
          • 57

          #5
          Originally posted by D_C
          Then make the range from 00 to 99, i.e. multiply the random value by 100, or take it modulo 100, depending on the range of the random value.

          Can You Give Me The Source?

          Comment

          • apsonline
            New Member
            • Aug 2006
            • 10

            #6
            hi
            may be this will help u out

            /* rand example */
            #include <stdio.h>
            #include <stdlib.h>
            #include <time.h>

            int main ()
            {
            /* initialize random generator */
            srand ( time(NULL) );

            /* generate some random numbers */
            printf ("A number between 0 and RAND_MAX (%d): %d\n", RAND_MAX, rand());
            printf ("A number between 0 and 99: %d\n", rand()%100);
            printf ("A number between 20 and 29: %d\n", rand()%10+20);

            return 0;
            }

            Output:
            A number between 0 and RAND_MAX (32767): 30159
            A number between 0 and 99: 72
            A number between 20 and 29: 23


            A good way to generate almost-true random numbers is to initialize the random algorithm using srand with the current time in seconds as parameter, as obtained from time function included in <time.h>.
            And, generally, a good way to get an integer random number between a range is to perform a module (%) operation on a result provided by rand():

            thus rand()%25 would be a random number between 0 and 24, both included.

            Comment

            Working...