C++隨機數產生,隨機數產生

來源:互聯網
上載者:User

C++隨機數產生,隨機數產生

<span style="font-size:14px;"><span style="font-size:14px;"></pre><pre code_snippet_id="617595" snippet_file_name="blog_20150312_2_2284349" name="code" class="cpp">                                      <pre name="code" class="cpp">                                                                                    //在這裡srand的作用很重要,srand()的作用是初始化隨機數種子,種子的偽隨機數計算的依據,//種子相同,計算得到的隨機數也是相同的,通常函數沒有用到srand()而是用rand(),則是相當於調用了srand(1),//這也解決了我上學期做最後那個記憶遊戲時,每次重新運行程式時,產生的隨機數都是相同的問題//time(NULL)返回的值是自1970.1.1零點以來經過的秒數,所以每時每刻都是不同的//#include<stdio.h>#include<time.h>//time()#include<stdlib.h>//srand()+rand()int main(){srand(time(NULL));//產生[a,b]int m = rand() % a + b;printf("%d\n", m);}</span></span>

<span style="font-size:14px;"><span style="font-size:14px;">//主要是產生隨機數,但是rand()函數產生隨機數區間為[0,RAND_MAX],//RAND_MAX至少為32767(2e15-1),並且在不同條件下數值可能不同//這裡作者用了放大的方式將區間放大(代碼來自劉汝佳)#include<stdio.h>#include<time.h>//time()#include<stdlib.h>//srand()+rand()int n = 100, m = 100000;//這個函數是取得[0,1]區間內的實數,之後在下一個函數中擴大(n-1)倍在取整double random(){return (double)rand() / RAND_MAX;}int random(int m){return (int)(random()*(m - 1) + 0.5);}int main(){srand(time(NULL));printf("%d %d\n", n, m);for (int i = 0; i < m; i++){if (rand() % 2 == 0){printf("A");}else{printf("B");}int X, Y;for (;;){X = random(n) + 1;Y = random(n) + 1;if (X != Y){break;}}printf("%d %d\n", X, Y);}return 0;}</span></span>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.