Random number generator, C++

后端 未结 8 2088
心在旅途
心在旅途 2020-12-10 18:25

I know there is a bit of limitations for a random number generation in C++ (can be non-uniform). How can I generate a number from 1 to 14620?

Thank you.

8条回答
  •  执念已碎
    2020-12-10 18:49

    The rand() function is not really the best Random generator, a better way would be by using CryptGenRandom().

    This example should do do the trick:

    #include 
    
    // Random-Generator
    HCRYPTPROV hProv;
    INT Random() {
        if (hProv == NULL) {
            if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_SILENT | CRYPT_VERIFYCONTEXT))
                ExitProcess(EXIT_FAILURE);
        }
    
        int out;
        CryptGenRandom(hProv, sizeof(out), (BYTE *)(&out));
        return out & 0x7fffffff;
    }
    
    int main() {
        int ri = Random() % 14620 + 1;
    }
    

提交回复
热议问题