C语言如何srand和rand函数产生10个1-100内的随机数
答案:4 悬赏:60 手机版
解决时间 2021-04-01 16:04
- 提问者网友:听门外雪花风
- 2021-04-01 01:30
C语言如何srand和rand函数产生10个1-100内的随机数
最佳答案
- 五星知识达人网友:神也偏爱
- 2021-04-01 02:43
先用srand函数设置一个种子,一般为当前时间,然后使用rand函数产生随机数,如产生a~b的随机数使用表达式rand()%(b-a+1)+a。
注意:srand函数在头文件#include中。
示例代码:
#include
#include
#include
int main()
{
int a[10], i;
srand((unsigned int)time(NULL));//设置当前时间为种子
for (i = 0; i < 10; ++i){
a[i] = rand()%100+1;//产生1~100的随机数
}
//打印生成的随机数
for (i = 0; i < 10; ++i){
printf ("%d ", a[i]);
}
printf ("
");
return 0;
}
注意:srand函数在头文件#include
示例代码:
#include
#include
#include
int main()
{
int a[10], i;
srand((unsigned int)time(NULL));//设置当前时间为种子
for (i = 0; i < 10; ++i){
a[i] = rand()%100+1;//产生1~100的随机数
}
//打印生成的随机数
for (i = 0; i < 10; ++i){
printf ("%d ", a[i]);
}
printf ("
");
return 0;
}
全部回答
- 1楼网友:神鬼未生
- 2021-04-01 04:00
#include "stdio.h"//
#include "stdlib.h"//
#include “time.h”//
void main(void){
int n,m,k;
printf("Type 2 integers...\nn=");
scanf("%d",&n);
printf("m=");
scanf("%d",&m);
srand((unsigned)time(NULL));
for(k=0;k printf("\n");
}
#include "stdlib.h"//
#include “time.h”//
void main(void){
int n,m,k;
printf("Type 2 integers...\nn=");
scanf("%d",&n);
printf("m=");
scanf("%d",&m);
srand((unsigned)time(NULL));
for(k=0;k
}
- 2楼网友:神也偏爱
- 2021-04-01 03:52
#include #include
#include
void t_rand(){srand(time(0)); // time -- seconds
int n=10, M=100;
for(int i=0; i printf("%.0f\t", 1.*rand()/RAND_MAX*M);
} // for
printf("\n");
} // t_rand
void main(){ t_rand(); return; }
#include
void t_rand(){srand(time(0)); // time -- seconds
int n=10, M=100;
for(int i=0; i
} // for
printf("\n");
} // t_rand
void main(){ t_rand(); return; }
- 3楼网友:逐風
- 2021-04-01 03:13
#include
#include
#include
#define N 10
#define M1 1
#define M2 100
void main()
{
int i=0,temp;
int a[N];
srand(time(0));
while(1)
{
temp=rand();
if((temp>=M1)&&(temp<=M2))
{
*(a+i) = temp;
printf("%d ",*(a+i));
i++;
}
if(i==N)break;
}
printf(" ");
}
追问你这个产生随机数后再判断大小,如果是1-100就输出,可能其实产生的是100个随机数,只有10个是1-100的,这样感觉有点浪费时间。。虽然都是瞬间就出来了。。能不能直接限制产生随机数的大小?追答#include
#include
#include
#define N 10
void main()
{
int i=0,temp;
int a[N];
srand(time(0));
while(1)
{
temp=rand()%100;
*(a+i) = temp;
printf("%d\n",*(a+i));
i++;
if(i==N)break;
}
printf("\n");
}追问rand()%100表示产生1-100的随机数,如果要生成x-y范围的随机数呢?追答实际上rand()%100只能是产生0到99之间的数。既然是srand是随机函数,就不应该会有范围的限制,有了限制的生成就不叫随机生成了。因此只能是通过判断来选择在x-y范围的随机数。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯