Hi! I am currently learning C, and I need help with generating random numbers. I use the Bloodshed compiler, and I do the normal thing for generating a number from 1 to, say, 5. It kinda works, but the 'random' number seems to increase along with the time every time I run it. Is there a way to fix this, or is there something wrong with the code?
I did a little searching and experimenting and came up with this to play with: Code: #include <stdio.h> #include <stdlib.h> #include <time.h> void PAUSE(void) { int c; while( (c=getc(stdin)) != EOF && c != '\n'); } /* also works to flush stdin when using scanf() */ int main(void) { int i, x, num; printf("\n ***** Some examples of using rand(): *****\n"); printf("\n The default of rand() is to generate a number from the set [0 - RAND_MAX]\n"); printf("My stdlib.h has RAND_MAX defined as = %d \n", RAND_MAX); printf("Here are some examples of usage : \n\n"); /**********/ printf("num = rand(); ...straight out of the box:\n\n"); for(i=0; i < 15; i++) { num = rand(); printf("%3d %i\n", i, num); } PAUSE(); /**********/ /* make a number from 1-5 instead */ /* num = ( ( (float)num/RAND_MAX) + 1) + 4; WHAT?? just do the following: */ printf("We can use the value returned by modulus to limit the set:\n"); printf("num = (rand() %% 6); \n\n"); for(i=0; i < 15; i++) { num = (rand() % 6) ; printf("%3d %i\n", i, num); } PAUSE(); /**********/ printf("We can modify that a little to set a bottom limit of the set:\n"); printf("num = (rand() %% 6); \nif(x > 2) num = x; \n\n"); for(i=0; i < 15; i++) { x = (rand() % 6) ; if(x > 2) { num = x; printf("%3d %i\n", i, num); } else i--; } printf("I noticed that the values for these two methods are the same each\n\ time program is run! This does does not occur, though, if same loop is called\n\ multiple times in the same run.\n\ Next I see how using the time to 'seed' rand() eliminates that predictability:\n"); PAUSE(); /********************************************************************/ printf("srand(time(NULL) ); \nnum = rand(); \n\n"); /* srand(TIME(NULL)); NO definition of 'TIME' ! */ /* srand(time(NULL) ); */ srand(time(0) ); /* same result */ for(i=0; i < 15; i++) { num = rand(); printf("%3d %i\n", i, num); /* of 1 - RAND_MAX */ } PAUSE(); for(i=0; i < 15; i++) { num = (rand() % 6) ; printf("%3d %i\n", i, num); } PAUSE(); return 0; } Post any questions you might still have...