We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent cfe4094 commit aa3fa01Copy full SHA for aa3fa01
1 file changed
经典项目/线性同余法产生随机数.c
@@ -1 +1,54 @@
1
-#
+//线性同余法产生随机数序列的公式为:
2
+// x[k+1] = (a*x[k] + c) % m
3
+
4
+//参数 a, c, m 都是由用户来设定的,并和一个种子数(例如 x[0])一起作为命令行参数传递给生成的程序。
5
6
+//一个简单的例子:a=7, c=1, m=13, and seed=5
7
8
+//一个复杂的例子:a=69069, c=0, m=2^32=4294967296, seed=31
9
10
+//下面的代码将输出一个随机数序列(最多有 m-1 个不同的值),然后继续循环。
11
12
13
+#include <stdio.h>
14
+#include <unistd.h>
15
+#include <stdlib.h>
16
+#include <Windows.h>
17
18
+static long seed = 13;
19
+static long a;
20
+static long c;
21
+static long m;
22
23
+void random_init(long s) {
24
+ if (s != 0) seed = s;
25
+}
26
27
+long random() {
28
+ seed = (a*seed + c)%m;
29
+ return seed;
30
31
32
+int main(int argc, char * argv[]) {
33
+ long s;
34
+ int k;
35
+ if (argc != 5) {
36
+ printf("usage: %s a, c, m, seed\n", argv[0]);
37
+ return 1;
38
+ }
39
+ a = atoi(argv[1]);
40
+ c = atoi(argv[2]);
41
+ m = atoi(argv[3]);
42
+ s = atoi(argv[4]);
43
+ random_init(s);
44
45
+ for (k = 0; k < m-1; k++) {
46
+ printf("%8ld", random());
47
+ if (k % 8 == 7) { // 输出 8 个数字以后换行
48
+ printf("\n");
49
+ Sleep(1); // 暂停 1 秒
50
51
52
53
+ return 0;
54
0 commit comments