模擬演算法資料結構與演算法 C++實現

來源:互聯網
上載者:User

標籤:

類比演算法:模擬的全過程,通過改變數學模型參數,進一步觀察狀態更改這些參數發生變化正當程式。


演算法思路:利用隨機函數來類比不可預測發生在自然界。(srand() 和 rand()函數產生一個隨機數)
類比演算法也就是將整個過程完完整整的走一遍。題目怎麼敘述的,程式就怎麼執行。

執行個體一:猜數字電腦隨機產生一個1-100的整數,使用者推測,每次推測給出不同的提示。代碼:

#include <iostream>#include <stdlib.h>#include <time.h>using namespace std;int main(){    srand(time(NULL));    int count=0;    int num = rand()%100 + 1;    int guess;    cout << "請輸入推測的數值:";    cin >> guess;    do{        if (guess > num){            count++;            cout << "您猜的值大了\n";            cout << "請再次輸入推測的數值:";            cin >> guess;        }else if (guess < num){            count++;            cout << "您猜的值小了\n";            cout << "請再次輸入推測的數值:";            cin >> guess;        }    }while(guess != num);        count++;        cout << "猜中了!

\n"; cout << "共猜了 " << count << " 次\n"; return 0;}

執行結果:
執行個體二:類比擲骰子遊戲由使用者自己輸入參與人數和骰子的個數。然後電腦隨機產生每一粒骰子的點數然後統計每一個人的點數。
代碼:
#include<iostream>#include<stdlib.h>#include<time.h>using namespace std;void play(int n);void play(int n){    int i,m=0,t=0;    for(i=0; i<n; i++)    {        t=rand()%6+1;        m+=t;        cout << "第" << (i+1) << "粒骰子的點數為:" << t <<"\n";    }    cout << "總共" << m << "點\n";}int main(){    int people,numbers;    do{        srand(time(NULL));        cout << "請輸入參與的人數:";        cin >> people;        if(people == 0) break;        cout << "請輸入骰子的數量:";        cin >> numbers;        if(numbers == 0) break;        for(int i=0; i<people; i++)        {            cout << "第 " << (i+1) << "位選手擲出的骰子情況為:\n";            play(numbers);        }    }while(1);    return 0;}
執行結果:

註:

C++產生隨機數的使用方法

1) 給srand()提供一個種子,它是一個unsigned int類型。

2) 調用rand(),它會依據提供給srand()的種子值返回一個隨機數(在0到RAND_MAX之間);

3) 依據須要多次調用rand()。從而不間斷地得到新的隨機數;

4) 不管什麼時候。都能夠給srand()提供一個新的種子,從而進一步“隨機化”rand()的輸出結果。

產生一定範圍隨機數的通用表示公式

要取得[a,b)的隨機整數,使用(rand() % (b-a))+ a;

要取得[a,b]的隨機整數,使用(rand() % (b-a+1))+ a;

要取得(a,b]的隨機整數,使用(rand() % (b-a))+ a + 1;

通用公式:a + rand() % n。其中a開始值,n範圍是一個整數。

著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。

模擬演算法資料結構與演算法 C++實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.