六月丁香五月婷婷,丁香五月婷婷网,欧美激情网站,日本护士xxxx,禁止18岁天天操夜夜操,18岁禁止1000免费,国产福利无码一区色费

學(xué)習(xí)啦>學(xué)習(xí)英語>專業(yè)英語>計(jì)算機(jī)英語>

c中random的用法

時(shí)間: 長(zhǎng)思709 分享

  下面小編就跟你們?cè)敿?xì)介紹下c中random的用法的用法,希望對(duì)你們有用。

  c中random的用法的用法如下:

  random函數(shù)不是ANSI C標(biāo)準(zhǔn),不能在gcc,vc等編譯器下編譯通過。但在C語言中int random(num)可以這樣使用,它返回的是0至num-1的一個(gè)隨機(jī)數(shù)。

  可改用C++下的rand函數(shù)來實(shí)現(xiàn)。

  rand()%n 范圍 0~n-1

  rand()主要是實(shí)現(xiàn) 產(chǎn)生隨機(jī)數(shù),其他我們?cè)谶@里可以無視他

  顯然任意 一個(gè)數(shù) rand()%n 范圍顯然是 0~n-1;

  那么 如何產(chǎn)生 n~m的數(shù)呢? 一樣的 我們只要對(duì)rand()進(jìn)行一些 符號(hào)操作就行了;

  n+rand()%(m-n+1); 這樣就可以了

  這樣我們 就只有 種子 和 浮點(diǎn)數(shù)的沒有分析了,

  下面來說rand()的用法 ,浮點(diǎn)數(shù)的放在最后面講 :一般在用這個(gè)之前 都要 初始化 一個(gè)種子 ,但是 你不寫的話,系統(tǒng)會(huì)給你 一個(gè)默認(rèn)的種子,下面是我們自己輸入種子的代碼;

  [cpp] view plain copy

  01.int seed;

  02.

  03.scanf ("%d",&seed);

  04.

  05.srand(seed);

  06.

  07.cout<<rand()<<endl;

  [cpp] view plain copy

  01.#include <stdio.h>

  02.#include <stdlib.h>

  03.#include <time.h>

  04.int 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 ("%d\t",rand()%10);

  14. printf ("\n");

  15. }

  16. return 0;

  17.}

  經(jīng)過下圖的比較發(fā)現(xiàn),每一個(gè)種子都是保持著這個(gè)狀態(tài)的隨機(jī)變量值,會(huì)存在系統(tǒng)里面;

  因此,我們要對(duì)這個(gè)初始化種子 保持著 時(shí)刻不同;也就是說 我們還是用 srand(time(NULL));比較好

  用如下代碼比較合適:

  [cpp] view plain copy

  01.#include <stdio.h>

  02.#include <stdlib.h>

  03.#include <time.h>

  04.int main()

  05.{

  06. //int arr[15];

  07. srand(time(NULL));

  08. for (int i=0; i<15; i++)

  09. printf ("%d\t",rand()%10);

  10. printf ("\n");

  11. while (1);

  12. return 0;

  13.}

  好了,我們現(xiàn)在講下最后一點(diǎn)---------浮點(diǎn)數(shù)的隨機(jī)產(chǎn)生

  rand()%n =========== 0~n-1 那么 我們?cè)俪?n 就行了

  可以表示為: (rand()%n)/(n*1.0) //這里注意下 隱式轉(zhuǎn)換 低------>高

  下面給出一個(gè)范例:

  [cpp] view plain copy

  01.#include <stdio.h>

  02.#include <stdlib.h>

  03.#include <time.h>

  04.int 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 ("%lf\t",(rand()%10)/10.0);

  14. printf ("\n");

  15. }

  16. return 0;

  17.}

537239