![]() ![]() It's good enough to deal cards for solitaire, but it's awful. Result = (rand() % (hi_num - low_num)) + low_num Low_num = max_num + 1 // include max_num in output Hi_num = max_num + 1 // include max_num in output Int random_number(int min_num, int max_num) Now, when we call rand(), a new random number will be produced every time. We do this by feeding it the value of the current time with the time() function. Therefore, we have to seed the randomizer with a value that is always changing. If you gave the same seed value, then the same random numbers would be generated every time. Basically, the computer can generate random numbers based on the number that is fed to srand(). First we use the srand() function to seed the randomizer. so we can expect to bail out of this loop pretty quickly.) (Worst case the loop condition should succeed 50% of the time, and ignore results from rand() that fall above that limit. elaborate implementation that combines multiple calls to rand() Supporting larger values for n would requires an even more * Uses rand(), and so is affected-by/affects the same seed. If you really care about uniformity you can do something like this: /* Returns an integer in the range [0, n). For example: /* random int between 0 and 19 */ It's common practice to use the % operator in conjunction with rand() to get a different range (though bear in mind that this throws off the uniformity somewhat). You can use srand(unsigned int seed) to set a seed. The rand() function in returns a pseudo-random integer between 0 and RAND_MAX. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |