MSDN中关于rand的描述"The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767). Use the srand function to seed the pseudorandom-number generator before calling rand." rand()产生的伪随机数的范围是0到32767,一般想要产生比如[5,125]的随机数,可以这么写: int x = rand()%120 + 5; 其中120是区间长度。 rand()产生的随机数是“伪随机数”,就是有可能在你的机器上运行,每次运行程序产生的随机数序列都是一样的,因此需要使用srand()解决这个问题: #include <time.h> srand(time(NULL)); //这句放在任何的rand()之前,且只需使用一次
rand函数
最新推荐文章于 2024-05-04 23:45:19 发布