C语言随机数生成超详解
生活随笔
收集整理的這篇文章主要介紹了
C语言随机数生成超详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.首先來看一段簡單的代碼
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h>int main(void) {int i;printf(" %6d\n", rand());system("pause"); }printf(" %6d\n", rand());system("pause"); }運行這個程序你會發現,每次重啟程序。
生成的隨機數都是固定的,這樣怎么還能叫隨機數呢
?
2.解決方法>srand()
srand()就是給rand()提供一個種子
srand(time);//這樣子可以打印出來符合要求的隨機數,但是我們要使用下面的形式為了time類型和srand類型統一,使用強制類型轉換(unsigned):
srand((unsigned) time(NULL));3.滿足需求的隨機數
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h>int main(void) {int i;srand((unsigned)time(NULL));for (i = 0; i < 10; i++){printf(" %6d\n", rand());}system("pause"); }?
?
?
?
總結
以上是生活随笔為你收集整理的C语言随机数生成超详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 秋去秋来剧情介绍
- 下一篇: C语言 浅谈可变参数