c语言怎么生成随机数?

定义一个数组,怎么生成100个随机数(范围为1000到2000).
在这个数组中怎么随机选取一个作为i?

你好!

完整的代码,红圈处就是从上面100个数字中抽取到的数字:

#include <stdio.h>
#include<stdlib.h>                  //生成随机数用 
#include<time.h>                    //利用时间生成种子 
#include<math.h>                    

int main()
{
      int i;
  int a[100];
      srand( time(NULL) );         //生成种子 

      for(i=0;i<100;i++)
      {
       a[i]=rand()%1000+1000;      //生成一个小于1000的随机数
                               //然后加1000,变成 1000 - 2000之间的数 
       printf("%d  ",a[i]);       //打印 
      }

       i=rand()%100;              //随机抽取其中的一个数 
       printf("\n抽取到的是:%d\n",a[i]);//打印 

      
      return 0; 
}

追问

i=rand()%100;不是生成1个小于100的随机数吗?怎么成了抽取其中的一个数

追答

因为上面的代码,已经将1000-2000的数字放在了a【100】的数组内;
要取出其中一个数字的时候,只需要生成 0 - 99 就能得到想要的数字了!

追问

怎么是从a[100]中取的呢?没有可能重新生成新的吗

追答

你的要求不是:在这个数组中怎么随机选取一个作为i?这样提的吗

你的意思是将这个取得的值,赋给 i  ??

#include <stdio.h>
#include<stdlib.h>                  //生成随机数用 
#include<time.h>                    //利用时间生成种子 
#include<math.h>                    

int main()
{
      int i;
  int a[100];
      srand( time(NULL) );         //生成种子 

      for(i=0;i<100;i++)
      {
       a[i]=rand()%1000+1000;      //生成一个小于1000的随机数
                               //然后加1000,变成 1000 - 2000之间的数 
       printf("%d  ",a[i]);       //打印 
      }

       i=rand()%100;              //随机抽取其中的一个数 

       i= a[i];                   // 这里把抽取的值赋给了 i  
       
   printf("\n抽取到的是:%d\n", i );//打印 i
      return 0; 
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-11-20
 #include <stdlib.h> 
 #include <stdio.h>
 #include <time.h> 
   void main() 
   { 
 srand((unsigned)time( NULL ) ); //时间种子有这个可以让每次运行程序产生的随机数不同
     for(int i=1;i<=100;i++) 
     { 
     printf("%d\t",rand()%1000+1000); //rand()函数产生的随机数的范围是-65535~65535
 if(i%8==0)
 printf("\n");
     } 
    }

 

如果对答案满意的话就麻烦把我的答案选为满意答案

追问

怎么数加入到数组呢?在这个数组中怎么随机选取一个作为i?

追答 #include <stdlib.h> 
 #include <stdio.h>
 #include <time.h> 
   void main() 
   { 
   int a[100],t;
   srand((unsigned)time( NULL ) ); 
     for(int i=1;i<=100;i++) 
     { 
     a[i-1]=rand()%1000+1000;//这样就可以了
 printf("%d\t",a[i-1]);
 if(i%6==0)
 printf("\n");
     } 
 printf("\n");
 printf("将随机抽取一个数\n");
 t=rand()%100;
 printf("抽取的是第%d个数\n",t+1);
 printf("%d\n",a[t]);//不知道是不是这个意思
    }

那个取一个作为i我不知道是什么意思!你能上传所有题目信息吗?

第2个回答  推荐于2017-09-18
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //用到了time函数
int main()
{ int i,number;
srand((unsigned) time(NULL)); //用时间做种,每次产生随机数不一样
for (i=0; i<50; i++)
{
number = rand() % 101; //产生0-100的随机数
printf("%d ", number);
}
return 0;
}
第3个回答  2013-11-20
srand函数 与rand函数配合使用,或者也可以用time函数,去看看srand和rand函数的用法
第4个回答  2020-05-10