有没有一个函数生成一个随机int数在C?或者我必须使用第三方库?
当前回答
#include <stdio.h>
#include <dos.h>
int random(int range);
int main(void)
{
printf("%d", random(10));
return 0;
}
int random(int range)
{
struct time t;
int r;
gettime(&t);
r = t.ti_sec % range;
return r;
}
其他回答
FWIW,答案是肯定的,有一个stdlib.h函数叫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 ;
}
在现代的x86_64 cpu上,您可以通过_rdrand64_step()使用硬件随机数生成器。
示例代码:
#include <immintrin.h>
uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
// Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number
<stdlib.h>中的rand()函数返回一个介于0和RAND_MAX之间的伪随机整数。你可以使用srand(unsigned int seed)来设置种子。
通常的做法是将%操作符与rand()结合使用以获得不同的范围(但请记住,这在一定程度上破坏了一致性)。例如:
/* random int between 0 and 19 */
int r = rand() % 20;
如果你真的在乎一致性,你可以这样做:
/* Returns an integer in the range [0, n).
*
* Uses rand(), and so is affected-by/affects the same seed.
*/
int randint(int n) {
if ((n - 1) == RAND_MAX) {
return rand();
} else {
// Supporting larger values for n would requires an even more
// elaborate implementation that combines multiple calls to rand()
assert (n <= RAND_MAX)
// Chop off all of the values that would cause skew...
int end = RAND_MAX / n; // truncate skew
assert (end > 0);
end *= n;
// ... and ignore results from rand() that fall above that limit.
// (Worst case the loop condition should succeed 50% of the time,
// so we can expect to bail out of this loop pretty quickly.)
int r;
while ((r = rand()) >= end);
return r % n;
}
}
推荐文章
- 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之间的随机数?