C++ programming generates random Numbers within a specified range

  • 2020-06-19 11:16:54
  • OfStack

C/C++ program to generate random Numbers within the specified range.


#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string>
#include <string.h>
 
/*
 *  Getting random Numbers 
 * return :  The random number 
 */
int commonGetRandNumber(const int low, const int high)
{
 int randNum = 0;
 
 // Random number generation 
 randNum = rand() % (high - low + 1) + low;
 
 return randNum;
}
 
#define RAND_MAX_LEN (16)
#define RAND_MIN_VALUE (0)
#define RAND_MAX_VALUE (9999)
 
/*
 *  Gets the string form of a random number 
 * return :  Random number string 
 */
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;
 
 // Random number generation 
 srand(time(0));
 randNum = commonGetRandNumber(low, high);
 
 snprintf(randArray, sizeof(randArray)-1, "%d", randNum);
 
 randStr = randArray;
 
 return randStr;
}
 
/*
 *  Gets to generate a random string based on a given character array and random Numbers 
 */
std::string getNonceStr(int length = 32)
{
 std::string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
 std::string str = "";
 
 // Random number generation 
 srand(time(0));
 for ( int i = 0; i < length; i++ )
 {
 str += chars.substr(commonGetRandNumber(0, chars.size() - 1), 1);
 }
 
 return str;
}
 
 
int main()
{
 
 // Getting random Numbers 
 srand(time(0));
 int randNum = commonGetRandNumber(10, 100);
 printf("randNum=%d\n", randNum);
 
 // Gets the string form of a random number 
 std::string randStr = commonGetRandString();
 printf("randStr=%s\n", randStr.c_str());
 
 // Gets to generate a random string based on a given character array and random Numbers 
 std::string randChar = getNonceStr();
 printf("randChar=%s\n", randChar.c_str());
 
}

Calling rand() produces a random number between [0,32757], and the absolute value of (high-low) cannot exceed 32767.


Related articles: