c中random的用法
下面小編就跟你們詳細介紹下c中random的用法的用法,希望對你們有用。
c中random的用法的用法如下:
random函數不是ANSI C標準,不能在gcc,vc等編譯器下編譯通過。但在C語言中int random(num)可以這樣使用,它返回的是0至num-1的一個隨機數。
可改用C++下的rand函數來實現。
rand()%n 範圍 0~n-1
rand()主要是實現 產生隨機數,其他我們在這裏可以無視他
顯然任意 一個數 rand()%n 範圍顯然是 0~n-1;
那麼 如何產生 n~m的數呢? 一樣的 我們只要對rand()進行一些 符號操作就行了;
n+rand()%(m-n+1); 這樣就可以了
這樣我們 就只有 種子 和 浮點數的沒有分析了,
下面來說rand()的用法 ,浮點數的放在最後面講 :一般在用這個之前 都要 初始化 一個種子 ,但是 你不寫的話,系統會給你 一個默認的種子,下面是我們自己輸入種子的代碼;
[cpp] view plain copy
seed;
02.
f ("%d",&seed);
04.
d(seed);
06.
<<rand()<<endl;
[cpp] view plain copy
01.#include <stdio.h>
02.#include <stdlib.h>
03.#include <time.h>
main()
05.{
06. int arr[15];
07. //srand(time(NULL));
08. int seed;
09. while(1){
10. scanf("%d",&seed);
11. srand(seed);
12. for (int i=0; i<15; i++)
13. printf ("%dt",rand()%10);
14. printf ("n");
15. }
16. return 0;
17.}
經過下圖的比較發現,每一個種子都是保持着這個狀態的隨機變量值,會存在系統裏面;
因此,我們要對這個初始化種子 保持着 時刻不同;也就是說 我們還是用 srand(time(NULL));比較好
用如下代碼比較合適:
[cpp] view plain copy
01.#include <stdio.h>
02.#include <stdlib.h>
03.#include <time.h>
main()
05.{
06. //int arr[15];
07. srand(time(NULL));
08. for (int i=0; i<15; i++)
09. printf ("%dt",rand()%10);
10. printf ("n");
11. while (1);
12. return 0;
13.}
好了,我們現在講下最後一點---------浮點數的隨機產生
rand()%n =========== 0~n-1 那麼 我們再除以 n 就行了
可以表示爲: (rand()%n)/(n*1.0) //這裏注意下 隱式轉換 低------>高
下面給出一個範例:
[cpp] view plain copy
01.#include <stdio.h>
02.#include <stdlib.h>
03.#include <time.h>
main()
05.{
06. int arr[15];
07. //srand(time(NULL));
08. int seed;
09. while(1){
10. scanf("%d",&seed);
11. srand(seed);
12. for (int i=0; i<15; i++)
13. printf ("%lft",(rand()%10)/10.0);
14. printf ("n");
15. }
16. return 0;
17.}