資料結構與演算法之類比演算法 C++實現,資料結構與演算法演算法

來源:互聯網
上載者:User

資料結構與演算法之類比演算法 C++實現,資料結構與演算法演算法
類比演算法:類比整個過程,通過改變數學中模型的各種參數,進而觀察變更這些參數所引起過程狀態的變化。
演算法思路:使用隨機函數來類比自然界中發生的不可預測情況。(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是整數的範圍。

聯繫我們

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