C/C++编程产生指定范围内的随机数,直接上个小程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#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。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u011857683/article/details/81155279