溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++隨機數字以及隨機數字加字母生成的方法

發布時間:2020-12-11 10:58:55 來源:億速云 閱讀:436 作者:小新 欄目:開發技術

這篇文章主要介紹C++隨機數字以及隨機數字加字母生成的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

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

C++隨機數字以及隨機數字加字母生成的方法

正確的方法,生成了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++隨機數字以及隨機數字加字母生成的方法

以上是“C++隨機數字以及隨機數字加字母生成的方法”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女