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;
}

 

相关文章:

  • 2021-06-22
  • 2021-12-31
  • 2021-11-30
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-06
  • 2019-08-29
  • 2022-12-23
相关资源
相似解决方案