c語言生成1~100隨機數(shù) C語言中如何生成一個隨機數(shù)組?
C語言中如何生成一個隨機數(shù)組?代碼:#include#include#include{srand((unsigned)time(null))int a[100]printf(”立即初始化100個數(shù)組的
C語言中如何生成一個隨機數(shù)組?
代碼:#include
#include
#include
{
srand((unsigned)time(null))
int a[100
]printf(”立即初始化100個數(shù)組的數(shù)目(范圍為0~100)。n“”
for(int I=0I
{
a[I]=rand() 1
printf(“m”,a[I])
if(I ==0&;I!=0)
printf(“ ”n“)
!getchar()
!]圖:
C語言如何隨機生成數(shù)組?
]你好
!完整代碼,紅色圓圈是從以上100個數(shù)字中提取的數(shù)字:
########include<stdlib。H>//生成隨機數(shù),使用
##########include<math。H>//隨時間生成種子
###########包含<math。H>
int main()
{
int i
int a[100
]srand(time(null))//生成種子
For(i=0I<100i)
{
a[i]=rand() 00 1000//生成一個小于1000的隨機數(shù)
//然后將1000加起來成為介于1000和2000之間的數(shù)
printf(%d”,a[i])//Print
}]i=rand() 0//隨機抽取其中一個數(shù)
printf(“n”,a[i])//Print
}]
C語言,如何隨機生成數(shù)組?
C語言獲取隨機數(shù)的函數(shù)是rand(),它可以得到一個非負整數(shù)隨機數(shù)。要調(diào)用Rand,需要引用頭文件stdlib。為了將隨機數(shù)限制在一定范圍內(nèi),我們可以使用模除加的方法。
要生成一個隨機數(shù)r,它的范圍是M
rand()%(n-m1)M
它的原理是,對于任何數(shù)字,
那么
0 M
就是
M