這篇文章主要介紹C++隨機數字以及隨機數字加字母生成的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
為大足等地區(qū)用戶提供了全套網頁設計制作服務,及大足網站建設行業(yè)解決方案。主營業(yè)務為成都網站建設、成都網站設計、大足網站設計,以傳統(tǒng)方式定制建設網站,并提供域名空間備案等一條龍服務,秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!#include <time.h> #include <sys/timeb.h> 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;
補充知識:C/C++生成隨機數字符串(錯誤方法和正確方法)
先說錯誤的方法。生成的10個隨機數是一樣的。
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> 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個不一樣的隨機數
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> 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個隨機數 // printf("\n====%s====\n",str); return 0; }
以上是“C++隨機數字以及隨機數字加字母生成的方法”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯行業(yè)資訊頻道!
網頁標題:C++隨機數字以及隨機數字加字母生成的方法-創(chuàng)新互聯
路徑分享:http://vcdvsql.cn/article22/ppccc.html
成都網站建設公司_創(chuàng)新互聯,為您提供營銷型網站建設、自適應網站、軟件開發(fā)、網站收錄、用戶體驗、ChatGPT
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯