有没有一个函数生成一个随机int数在C?或者我必须使用第三方库?
当前回答
您希望使用rand()。注意(非常重要):确保为rand函数设置了种子。如果你不这样做,你的随机数就不是真正的随机。这是非常、非常、非常重要的。值得庆幸的是,您通常可以使用系统滴答计时器和日期的某种组合来获得良好的种子。
其他回答
试试这个,我把上面已经提到的一些概念放在一起:
/*
Uses the srand() function to seed the random number generator based on time value,
then returns an integer in the range 1 to max. Call this with random(n) where n is an integer, and you get an integer as a return value.
*/
int random(int max) {
srand((unsigned) time(NULL));
return (rand() % max) + 1;
}
你可以生成随机字符,然后将它们视为int:
#include <stdlib.h>
#include <stdio.h>
typedef double rand_type; // change double to int
rand_type my_rand() {
char buff[sizeof(rand_type)];
for (size_t i = 0 ; i < sizeof(rand_type) ; ++i)
buff[i] = (char) rand();
return *(rand_type *) buff;
}
int main() {
int i ; // srand as you want
for (i = 0 ; i < 10 ; ++i)
printf("%g\n", my_rand()); // change %g to %d
return 0 ;
}
注意:为了安全性,不要使用rand()。如果您需要加密安全的号码,请参阅此答案。
#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.
在Linux上,您可能更喜欢使用random和srandom。
希望这比仅仅使用srand(time(NULL))更随机。
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL));
srand(rand());
for (int i = 0; i < 10; i++)
printf("%d\n", rand());
}
你也可以使用mathgl库#include <mgl2/mgl_cf.h>(虽然首先你需要安装它,我自己通过MSYS2安装)函数mgl_rnd()。它也有均匀分布,高斯分布等等。这是ez的用法。但我不知道它的特点。
推荐文章
- C多行宏:do/while(0) vs作用域块
- 生成具有给定(数值)分布的随机数
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?
- 函数名周围的括号是什么意思?
- 用C语言创建自己的头文件
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- main()中的Return语句vs exit()
- 如果不是内存地址,C指针到底是什么?
- 在php中生成一个随机密码
- GLSL的随机/噪声函数
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- java.util.Random和java.security. securerrandom的区别
- 保护可执行文件不受逆向工程的影响?
- 0到1之间的随机数?