//------------------------------------------------------------------ #include <stdlib.h> // rand() srand() ... /* rand() function is not guaranted to produce random values */ int random; // the same value between 0 and RAND_MAX // for every run random = rand(); ... //------------------------------------------------------------------ ... float random; // the same value between 0 and 1.0 // for every run random = (float) rand() / RAND_MAX; ... //------------------------------------------------------------------ ... #define N 42 ... int random; // the same value between 0 and N -1 // for every run random = (int)( N * (double)rand() / (RAND_MAX + 1.0) ); ... |
//------------------------------------------------------------------ #include <stdlib.h> // rand() srand() #include <time.h> // time() ... int random; // seeds a new sequence of random number srand(time(NULL)); // a different value between 0 and RAND_MAX // for every run random = rand(); ... |
//------------------------------------------------------------------ /* under Linux /dev/random or /dev/urandom */ #include <stdio.h> // FILE *, fopen(), fread(), fclose() ... FILE * fp; unsigned int random; if ((fp = fopen("/dev/random","r")) == NULL) { perror("fopen"); exit(1); } fread(&random, sizeof(random), 1, fp); printf("random number %u from /dev/random\n", random); fclose(fp); ... //------------------------------------------------------------------ |