rand.h
#ifndef RAND_H
unsigned long int next = 1;
int rand() {
next = next * 1103515245 + 12345;
return (unsigned int)(next/65535) % 32768;
}
void seed(unsigned int seed) {
next = seed;
}
#endif
main.c
#include <stdio.h>
#include "rand.h"
int main(int argc, char **argv) {
int num;
while (1) {
printf("Please enter the seed\n");
scanf("%d", &num);
seed(num);
printf("The value is %d\n", rand());
}
return 0;
}
使用%取模可以用于产生任意整形范围内的随机数。
本文介绍了一个基于C语言的简单随机数生成器实现,通过使用线性同余方法,结合用户输入的种子来生成随机数。代码中包含了rand.h头文件定义和main.c主程序,演示了如何设置种子并生成介于指定范围内的随机数。

被折叠的 条评论
为什么被折叠?



