C语言如何srand和rand函数产生10个1-100内的随机数

10个是任意的,也可能是100个,1-100也是任意的。。。求解,详细的有追加

需要准备的材料分别有:电脑、C语言编译器

1、首先,打开C语言编译器,新建一个初始.cpp文件,例如:test.cpp。

2、在test.cpp文件中,输入C语言代码:

for (int i = 0; i < 10; i++)

printf("%d ", rand() % 100 +1);

3、编译器运行test.cpp文件,此时成功通过rand产生了10个1-100内的整数。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-01

先用srand函数设置一个种子,一般为当前时间,然后使用rand函数产生随机数,如产生a~b的随机数使用表达式rand()%(b-a+1)+a。

注意:srand函数在头文件#include <stdlib.h>中。

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    int a[10]/*用于保存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 ("\n");
    return 0;
}

第2个回答  推荐于2017-10-15

#include <stdlib.h>

#include <stdio.h>

#include <time.h>

#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\n",*(a+i));

i++;

}

if(i==N)break;

printf("\n");

追问

你这个产生随机数后再判断大小,如果是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范围的随机数。

本回答被提问者采纳
第3个回答  2013-03-17
#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<n;printf("%d ",rand()%m),k++);
printf("\n");
}
第4个回答  2013-03-17
#include <stdio.h> #include <stdlib.h>
#include <time.h>

void t_rand(){srand(time(0)); // time -- seconds
int n=10, M=100;
for(int i=0; i<n; i++){
printf("%.0f\t", 1.*rand()/RAND_MAX*M);
} // for
printf("\n");
} // t_rand

void main(){ t_rand(); return; }
相似回答