我是靠谱客的博主 痴情小熊猫,这篇文章主要介绍C++实现输出随机数的四个小程序,现在分享给大家,希望可以做个参考。

github:传送门,码云:传送门
1、此程序会输出 0~abs(x-1) 的随机数
rand函数配合srand生成随机种子使产生的随机数改变

复制代码
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
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand((int)time(0)); // 产生随机种子 cout << "此程序会输出 0~abs(x-1) 的随机数" << endl; while(1) { int x; cout << endl << "输入x:"; cin >> x; if(x == 0) { cout << "x不能为0" << endl; continue; } cout << rand()%(x) << endl; // 0~abs(x-1) } return 0; }

2、此程序会输出 x~x+abs(y-1) 的随机数

复制代码
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
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand((int)time(0)); // 产生随机种子 int x,y; cout << "此程序会输出 x~x+abs(y-1) 的随机数" << endl; while(1) { cout << endl << "最小值:"; cin >> x; cout << "偏移值:"; cin >> y; if(y == 0) { cout << "偏移值不能为0" << endl; continue; } cout << rand()%(y)+x << endl; // x~x+abs(y-1) } return 0; }

3、此程序会输出abs(n)个 x~x+abs(y-1) 的随机数

复制代码
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
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand((int)time(0)); // 产生随机种子 int x,y,n; cout << "此程序会输出abs(n)个 x~x+abs(y-1) 的随机数" << endl; while(1) { cout << endl << "输出几个随机数:"; cin >> n; if(n < 0) { n = 0-n; } cout << "最小值:"; cin >> x; cout << "偏移值:"; cin >> y; if(y == 0) { cout << "偏移值不能为0" << endl; continue; } for(int i=0; i<n; i++) { cout << rand()%(y)+x << " "; // x~x+abs(y-1) } cout << endl; } return 0; }

4、此程序会输出abs(n)个 不重复的 x~x+abs(y-1) 的随机数
使用STL模板库的set来做到去重的功能

复制代码
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
#include <iostream> #include <cstdlib> #include <ctime> #include <set> using namespace std; int main() { //cout << "s:" << s.size() << endl; srand((int)time(0)); // 产生随机种子 int x,y,n; cout << "此程序会输出abs(n)个 不重复的 x~x+abs(y-1) 的随机数" << endl; while(1) { set<int> s; // 使用模板库的set来做到去重 cout << endl << "输出几个随机数:"; cin >> n; if(n < 0) { n = 0-n; } cout << "最小值:"; cin >> x; cout << "偏移值:"; cin >> y; if(y == 0) { cout << "偏移值不能为0" << endl; continue; } if(y < n) { cout << "偏移值不能小于需要的随机数的个数" << endl; continue; } while(1) { if(n == s.size()) { //cout << "n:" << n << endl; break; } int size1 = s.size(); int temp = rand()%(y)+x; s.insert(temp); int size2 = s.size(); if(size1 != size2) { cout << temp << " "; // x~x+abs(y-1) } } cout << endl; } return 0; }

如有错误望指出

最后

以上就是痴情小熊猫最近收集整理的关于C++实现输出随机数的四个小程序的全部内容,更多相关C++实现输出随机数内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部