Windows CE系统生成随机数字符串

本文介绍如何使用srand和rand函数生成随机数,特别是在Windows CE环境下使用GetTickCount替代time函数的方法,并提供了一个生成指定长度随机字符串的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

srand函数用于初始化随机数生成器,rand函数用于产生随机数。srand的参数称为随机数种子,要确保rand函数产生真正的随机数(每次生成的随机数不同),随机数种子就要设置为不同的值。(In order to generate random-like numbers, srand is usually initialized to some distinctive value)

通常以系统时间作为随机数种子,最常用的方式是:srand(time(NULL));,但Windows CE编程时,c库不支持time函数,所以这里以GetTickCount代替。另外注意下面函数中的for循环,由于for循环执行速度很快,所以在(unsigned)GetTickCount()之后加上一个i很必要。

CString GetRandomString(int string_length)
{
    CString string_temp, string_result;
    const TCHAR number_array[] = _T("0123456789");

    for (int i = 0; i < string_length; ++i)
    { 
        srand((unsigned)GetTickCount() + i);
        int x = rand()%10;
        string_temp.Format(_T("%c"), number_array[x]); 
        string_result += string_temp; 
    }

    return string_result;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值