Random number problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sake
    New Member
    • Jan 2007
    • 46

    Random number problem

    Hi,
    I have a program that generates a random number for each run of a loop, like this:

    <snippet>:
    int i;
    int n;

    for(i=0;i<=10;i ++){
    n = rand() / (RAND_MAX / 10 + 1);
    printf( "n: %d\n", n );
    }

    Obviously using the time to seed rand() each run wouldn't work because progressing through the loop ten times does not take a second of time. So how would I go about seeding rand() in my program to get 10 different random numbers in my loop?

    Thanks,
    Sake
  • baroon
    New Member
    • Jan 2007
    • 12

    #2
    dear Sake,
    i want to know does this formulla ( printf( "n: %d\n", n ) )in c++???? because i think its in c not c++?!?!?!?!?!?! ?!?!?


    and if u know if i can use other furmulla with same meaning please tell me befor wednesday


    and i will apreasuated to u :)

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Originally posted by sake
      Obviously using the time to seed rand() each run wouldn't work because progressing through the loop ten times does not take a second of time. So how would I go about seeding rand() in my program to get 10 different random numbers in my loop?
      You only need to seed the random number generator once for each program execution so you can seed it off time and then happily generate 10 random numbers.

      Code:
      <snippet>:
      int i;
      int n;
      
      srand(time(NULL));
      
      for(i=0;i<=10;i++){
        n = rand() / (RAND_MAX / 10 + 1);
        printf( "n: %d\n", n );

      Comment

      • sake
        New Member
        • Jan 2007
        • 46

        #4
        Originally posted by baroon
        dear Sake,
        i want to know does this formulla ( printf( "n: %d\n", n ) )in c++???? because i think its in c not c++?!?!?!?!?!?! ?!?!?


        and if u know if i can use other furmulla with same meaning please tell me befor wednesday


        and i will apreasuated to u :)
        yeah that's in C...
        its just a simple printf statement... not really a formula :\

        And thanks, Banfa, i'll try that when i get home :)

        Comment

        • sake
          New Member
          • Jan 2007
          • 46

          #5
          Originally posted by sake
          yeah that's in C...
          its just a simple printf statement... not really a formula :\

          And thanks, Banfa, i'll try that when i get home :)
          yeah it worked :) thanks alot

          Comment

          Working...