C語言程序設(shè)計從入門到進階【比特鵬哥c語言2023完整版視頻教程】(c語言基礎(chǔ)入

=====隨機數(shù)代碼詳解======
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
//隨機數(shù)?
int main() {
//1.獲取一個偽隨機數(shù) 每次都是固定的
??int r=?rand();
??printf("獲取一個偽隨機數(shù):%d\n",r);
??//2.通過定義隨機種子 獲得隨機數(shù)
??srand((unsigned int)100); //但是隨機種子依然固定
??int a=?rand();
??printf("通過定義隨機種子 獲得隨機數(shù):%d\n",a);
??
??//3.設(shè)置真正的隨機值
??int times =time(NULL); //獲取一個時間戳
??srand((unsigned int)times);
??int b=?rand();
??printf("時間戳:%d,設(shè)置真正的隨機值獲得隨機數(shù):%d\n",times,b);
???
??//4.獲取1-100的隨機數(shù) 10個
srand((unsigned int)time(NULL));
for(int i=0;i<=10;i++){
int c=?rand()%100+1;//rand()%100表示0-99的數(shù)字 +1 就是100
??printf("獲取1-100的隨機數(shù):%d\n",c);
}
//5.獲取 10-20這個范圍內(nèi)的10個隨機數(shù)
int x,y,start=10,end=20;
srand((unsigned int)time(NULL));
for(int i=0;i<=10;i++){
int d=rand()%start+1+(end-start);//%開始的值+1 再加上區(qū)間長度即可
printf("獲取 10-20這個范圍內(nèi)的隨機數(shù):%d\n",d);
}
}