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;


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值