VC++中如何产生一个随机数?

我们可以使用 CRT 中的 rand 函数来产生一个随机数。在调用rand前,请使用srand()函数设置种子,这个函数能触发随机数发生器(RNG)产生一个相对特定的值(主要是根据当前的时间)。

代码:

int randNumber
srand(time(NULL))
randNumber = rand();

Windows里,我们还可以选择使用Cryptography中的CryptGenRandom函数,这函数可以在缓冲区中填入cryptographically随机字节。

一个产生0-100的随机数的代码:

#include"stdafx.h
#includ <iostream>
#includ <windows.h>
usingnamespace std
#pragmacomment(lib,"crypt32.lib"
#includ <Wincrypt.h>

#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

int main()

{

   //--------------------------------------------------------------------

   // Declare and initialize variables.

    HCRYPTPROV   hCryptProv;

    BYTE         pbData

   //-------------------------------------------------------------------

   // Acquire a cryptographic provider context handle.

 

   if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0)) 

    {   

        printf("CryptAcquireContext succeeded. \n");

    }

   else

    {

        printf("Error during CryptAcquireContext!\n");

    }

   //--------------------------------------------------------------------

   // Generate a random BYTE.

 

   if(CryptGenRandom(hCryptProv, 1, &pbData))

    {

        printf("Random number is: %d.\n", ((int)pbData) * 100 / 255);

    }

   else

    {

        printf("Error during CryptGenRandom.\n")
        exit(1);

    }

 

   //-------------------------------------------------------------------

   // Clean up

   if(hCryptProv)

    {

       if (!CryptReleaseContext(hCryptProv, 0))

        {

            printf("Failed CryptReleaseContext\n");

        }

    }

   return 0;


你可能感兴趣的:(windows,null,Random,vc++,encoding,Cryptography)