C/C++编程产生指定范围内的随机数,直接上个小程序:

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string>
#include <string.h>

/*
 * 获取随机数
 * return : 随机数
 */
int commonGetRandNumber(const int low, const int high)
{
 int randNum = 0;

 //生成随机数
 randNum = rand() % (high - low + 1) + low;

 return randNum;
}

#define RAND_MAX_LEN  (16)
#define RAND_MIN_VALUE (0)
#define RAND_MAX_VALUE (9999)

/*
 * 获取随机数的字符串形式
 * return : 随机数字符串
 */
std::string commonGetRandString()
{
 int low  = RAND_MIN_VALUE;
 int high = RAND_MAX_VALUE;
 int randNum = 0;
 char randArray[RAND_MAX_LEN] = {0};
 std::string randStr;

 //生成随机数
 srand(time(0));
 randNum = commonGetRandNumber(low, high);

 snprintf(randArray, sizeof(randArray)-1, "%d", randNum);

 randStr = randArray;

 return randStr;
}

/*
 * 获取根据给定字符数组和随机数生成随机字符串
 */
std::string getNonceStr(int length = 32)
{
 std::string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
 std::string str = "";

 //生成随机数
 srand(time(0));
 for ( int i = 0; i < length; i++ )
 {
  str += chars.substr(commonGetRandNumber(0, chars.size() - 1), 1);
 }

 return str;
}


int main()
{

 //获取随机数
 srand(time(0));
 int randNum = commonGetRandNumber(10, 100);
 printf("randNum=%d\n", randNum);

 //获取随机数的字符串形式
 std::string randStr = commonGetRandString();
 printf("randStr=%s\n", randStr.c_str());

 //获取根据给定字符数组和随机数生成随机字符串
 std::string randChar = getNonceStr();
 printf("randChar=%s\n", randChar.c_str());

}

调用rand()会产生[0,32757]之间的随机数,(high - low)的绝对值不能超过32767。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

01-18 16:17