Continuously generating a random number in C

srand () Set random seed

rand () generates a 0 - a random number range RAND_MAX

Plus other operations, we are able to generate random numbers in any range. rand () is a random number sequence output of a random number table inside. Therefore, if the random number seed is not set, the generated random number is fixed.

int main () 
{ 
    char STR [ 10 ] = { 0 };
     int J = 0 ; 
    the while (J < 10 ) 
    { 
// generate three random numbers
int I = strlen (STR); for (; I < . 3 ; ++ I ) { STR [I] = ' 0 ' + RAND ()% 10 ; }

// generates two random letters STR [I
++] = ' A ' + RAND ()% 26 is ; STR [I] =' A ' + RAND ()% 26 is ;
// output the printf (STR); the printf (
" \ n- " ); J ++ ; STR [ 0 ] = ' \ 0 ' ; } return ( 0 ); }

Each time you run the program will produce the same results

As shown for the first time: the second run:

Thus with srand () after the attempt to set seed, as follows

#include <stdio.h> 
#include < String .h> 
#include <stdlib.h> int main () 
{ char STR [ 10 ] = { 0 };
     int J = 0 ; the while (J < 10 ) 
    { 
                srand ( (unsigned) time (NULL)); // add a time the random number seed int I =   strlen (STR);
         for (; I < . 3 ; I ++ ) { 
            STR [I] = ' 0 ' + RAND (%) 10 ;




    
    
    

         
        }
        str[i++] = 'A' + rand() % 26;
        str[i] = 'A' +rand() % 26;
        printf(str);
        printf("\n");
        j++;
        str[0] = '\0';
    }
    return(0);
}


            

Operation, because srand statements inside the loop, each time with seeding time, program execution speed is fast, the accuracy of the acquisition time, numerical inconvenient, so each cycle is the same, if the srand () on the outer loop , can produce various different sequences: this result is the following:

 

 

 The look is desired results

If I try to turn srand () while on the inside of it, also, we can write

#include <stdio.h>
#include <string.h>
#include <stdlib.h>



int main()
{
    char str[10] = {0};
    int j =0;
    while(j < 10)
    {
                srand((unsigned)time(NULL) + (unsigned)rand());
        int i =  strlen(str);
        for (;i < 3;i++){
            str[i] = '0' + rand() % 10;
        }
        str[i++] = 'A' + rand() % 26;
        str[i] = 'A' +rand() % 26;
        printf(str);
        printf("\n");
        j++;
        str[0] = '\0';
    }
    return(0);
}


    

Plus the time to do a random number seed, but the original aim, the last random number generator or by time, but after adding a random number it also depends on the number of calls you cycle inside rand () at any rate, when the program determining, time determination, the generated random number is the same.

 

Guess you like

Origin www.cnblogs.com/dosu/p/12468150.html