有没有一个函数生成一个随机int数在C?或者我必须使用第三方库?
当前回答
在现代的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
其他回答
在现代的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
希望这比仅仅使用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());
}
C程序生成9到50之间的随机数
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int lowerLimit = 10, upperLimit = 50;
int r = lowerLimit + rand() % (upperLimit - lowerLimit);
printf("%d", r);
}
通常我们可以生成一个介于lowerLimit和upperLimit-1之间的随机数
例如,lowerLimit包含或说r∈[lowerLimit, upperLimit)
看看ISAAC(间接,移动,积累,添加和计数)。它是均匀分布的,平均循环长度为2^8295。
试试这个,我把上面已经提到的一些概念放在一起:
/*
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;
}