C语言随机字母生成,C++ 随机数字以及随机数字加字母生成的案例
我就廢話不多說了,大家還是直接看代碼吧~
#include
#include
void MainWindow::slot_clicked()
{
QString strRand;
int length = 32;
QString strTmp = "1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
struct timeb timer;
ftime(&timer);
srand(timer.time * 1000 + timer.millitm);//毫秒種子
for(int i = 0; i < length; i++ )
{
int j = rand()%35;
strRand += strTmp.at(j);
}
qDebug() << strRand;
補(bǔ)充知識:C/C++生成隨機(jī)數(shù)字符串(錯(cuò)誤方法和正確方法)
先說錯(cuò)誤的方法。生成的10個(gè)隨機(jī)數(shù)是一樣的。
#include
#include
#include
#include
void make_rand_str(char *pchStr,int iLen)
{
time_t tCurTime = 0;
int iRandValue = 0;
int i = 0;
unsigned int state = 0;
if(NULL == pchStr || iLen <= 0)
{
return;
}
tCurTime = time(NULL);
printf("\n***%ld***%u**\n",tCurTime ,(unsigned int)tCurTime);
srand((unsigned int)tCurTime);
iRandValue = rand();
snprintf(pchStr,iLen,"%d",iRandValue);
printf("\n====%s====\n",pchStr);
return;
}
int main()
{
char str[20];
int i = 0;
for(i = 0; i < 10; i++)
{
memset(str,0,sizeof(str));
make_rand_str(str,sizeof(str));
// printf("\n====%s====\n",str);
}
return 0;
}
正確的方法,生成了10個(gè)不一樣的隨機(jī)數(shù)
#include
#include
#include
#include
void make_rand_str(char *pchStr,int iLen,int num)
{
time_t tCurTime = 0;
int iRandValue = 0;
int i = 0;
unsigned int state = 0;
if(NULL == pchStr || iLen <= 0)
{
return;
}
tCurTime = time(NULL);
printf("\n***%ld***%u**\n",tCurTime ,(unsigned int)tCurTime);
srand((unsigned int)tCurTime);
for(i = 0;i < num; i++)
{
iRandValue = rand();
snprintf(pchStr,iLen,"%d",iRandValue);
printf("\n====%s====\n",pchStr);
}
return;
}
int main()
{
char str[20];
memset(str,0,sizeof(str));
make_rand_str(str,sizeof(str),10); // 10個(gè)隨機(jī)數(shù)
// printf("\n====%s====\n",str);
return 0;
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方歡迎留言討論,望不吝賜教。
總結(jié)
以上是生活随笔為你收集整理的C语言随机字母生成,C++ 随机数字以及随机数字加字母生成的案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 谁知道这是啥电影恐怖片,香港的
 - 下一篇: 是不是改变盘古形态,就不能变坐骑