1. 程式人生 > 程式設計 >C++ 隨機數字以及隨機數字加字母生成的案例

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,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",(unsigned int)tCurTime);
  srand((unsigned int)tCurTime); 
  for(i = 0;i < num; i++)
  {
    iRandValue = rand();
    snprintf(pchStr,iRandValue);
    printf("\n====%s====\n",pchStr);
  }  
  return;
}
 
int main()
{
  char str[20]; 
  memset(str,sizeof(str));
  make_rand_str(str,sizeof(str),10); // 10個隨機數
  // printf("\n====%s====\n",str);  
  return 0; 
}

C++ 隨機數字以及隨機數字加字母生成的案例

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方歡迎留言討論,望不吝賜教。