点击查看代码
#include<cstdio>
#include<stdlib.h> //使用srand()和rand()
#include<time.h> //使用time()
#include<cmath> //使用round()
#pragma warning(disable:4996)
int main() {
srand((unsigned)time(NULL)); //生成随机数的种子
//rand()生成随机数范围[0,RAND_MAX]
for (int i = 0; i < 10; i++) {
printf("%d ", rand());
}
printf("\n");
//rand()%(b-a+1)+a,随机数范围[a,b],左右端点相差不能超过RAND_MAX
for (int i = 0; i < 10; i++) {
printf("%d ", rand() % 5 + 3); //随机数范围[3,7]
}
printf("\n");
//(int)(round(1.0 * rand() / RAND_MAX * (b-a) + a)),随机数范围[a,b],左右端点相差可以超过RAND_MAX
//round(x)返回x的四舍五入整数值
for (int i = 0; i < 10; i++) {
printf("%d ", (int)(round(1.0 * rand() / RAND_MAX * 50000 + 10000))); //随机数范围[10000,60000]
}
printf("\n");
return 0;
}