Rand generating same numbers

前端 未结 3 756
粉色の甜心
粉色の甜心 2021-01-21 11:52

I have a problem with the small game that I made.

#include \"stdafx.h\"
#include 
#include 
#include 
using namespace         


        
3条回答
  •  耶瑟儿~
    2021-01-21 11:57

    [ADDITION1]

    If you DO truly wish to look into better random number generation, then this is a good algorithm to begin with:

    http://en.wikipedia.org/wiki/Mersenne_twister

    Remember though that any "Computer Generated" (i.e. mathematically generated) random number is ONLY pseudo-random. Pseudo-random means that while the outputs from the algorithm look to have normal distribution, they are truly deterministic if one knows the input seed. True random numbers are completely non-deterministic.

    [ORIGINAL] Try simply one of the following lines:

    rand() % (span + 1);  // This will give 0 - 100
    rand() % span;        // this will give 0 - 99
    rand() % span + 1;    // This will give 1 - 100
    

    Instead of:

    (rand()) /RAND_MAX * (span -1) +1
    

    Also, don't cast the result of that to a double, then place into an int.

    Look here also:

    http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

    In Response to the comment!!! If you use:

    rand() / (span + 1);
    

    then in order to get values between 0 and 100, then the output values from rand would indeed have to be between 0 and (100 * 100), and this nature would have to be guaranteed. This is because of simple division. A value of 1 will essentially pop out when rand() produces a 101 - 201, a 2 will pop out of the division when the rand() outputs a value of 202 - 302, etc...

    In this case, you may be able to get away with it at 100 * 100 is only 10000, and there are definitely integers larger than this in the 32 bit space, but in general doing a divide will not allow you to take advantage utilizing the full number space provided!!!

提交回复
热议问题