C語言生成隨機數代碼


 1 #include <stdio.h>
 3 #include <stdlib.h>
 5 #include <time.h>
 7 int main() {
 9     int a;
11     srand((unsigned)time(NULL));  //讀取系統時間,產生一個種子數值
13     a = rand();
15     printf("%d\n", a);    //可擴展為驗證碼代碼
17     return 0;
19 }

生成一定范圍內的隨機數

在實際開發中,我們往往需要一定范圍內的隨機數,過大或者過小都不符合要求,那么,如何產生一定范圍的隨機數呢?我們可以利用取模的方法:

int a = rand() % 10;    //產生0~9的隨機數,注意10會被整除

如果要規定上下限:

int a = rand() % 51 + 13;    //產生13~63的隨機數

分析:取模即取余,rand()%51+13我們可以看成兩部分:rand()%51是產生 0~50 的隨機數,后面+13保證 a 最小只能是 13,最大就是 50+13=63。

代碼示例:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int a;
srand((unsigned)time(NULL));
a = rand() % 51 + 13;
printf("%d\n",a);
return 0;
}

 




 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM