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");
}
?
?
?
?