亂數rand()在stdlib.h中,

 題目:兩有A、B兩人互相擲骰子比大小,B有特異功能可以決定骰子每個數字的出現機率。贏的人得5元,輸的人賠5元,可以欠錢。

Input:B的6個數字出現機率,這六個數字機率總和必須100%,否則throw except "Wrong input"

Output:兩人互猜100次後,誰贏誰輸、贏幾元


#include <stdlib.h>
#include <iostream>
#include <ctime>
#include <stdexcept>
using namespace std;

class A
{
private:
    int money;
    int number;
public:
    A()
    {
        money=0;
    }

    int getMoney()
    {
        return money;
    }

    void setMoney(int n)
    {
        money += n;
    }

    int getNumber()
    {
        return number;
    }

    void thinkNumber()
    {
        number = (rand()%6)+1;  /*任意數除以6的餘數有0、1、2、3、4、5;"+1"後得到1、2、3、4、5、6*/
    }
};

class B
{
private:
    int one,two,three,four,five,six;
    int money;
    int number;
    int table[100];  /*若要自訂義個別數字的出現機率,可以用這個方法:用矩陣來裝不同數量的數字,並用rand()來決定區間*/
public:
    B()
    {
        money=0;
    }

    int ThinkRand6()
    {
        cin>>one>>two>>three>>four>>five>>six;
        int sum=one+two+three+four+five+six;

        if(sum!=100)
        {
            throw invalid_argument{
            "wrong input"};
            return 1;
        }


        int i;
        for(i=0;i<one;i++)
        {
            table[i]=1;
        }
        for(i=one;i<one+two;i++)
        {
            table[i]=2;
        }
        for(i=one+two;i<one+two+three;i++)
        {
            table[i]=3;
        }
        for(i=one+two+three;i<one+two+three+four;i++)
        {
            table[i]=4;
        }
        for(i=one+two+three+four;i<one+two+three+four+five;i++)
        {
            table[i]=5;
        }
        for(i=one+two+three+four+five;i<one+two+three+four+five+six;i++)
        {
            table[i]=6;
        }

        return 0;
    }

    int getMoney()
    {
        return money;
    }

    void setMoney(int n)
    {
        money += n;
    }

    int getNumber()
    {
        return number;
    }

    void thinkNumber()
    {
        number = table[(rand()%100)+1];
    }
};

int main()
{
    srand(time(NULL));
    A personA;
    B personB;

    int j=1;
    for(;j;)
    {
        try
        {
            j=personB.ThinkRand6();
        }catch(invalid_argument &e){
        cout<<e.what()<<endl;
        }
    }

    int i;
    for(i=0;i<1000;i++)
    {
        personA.thinkNumber();
        personB.thinkNumber();

    if(personA.getNumber()>personB.getNumber())
    {
        personA.setMoney(5);
        personB.setMoney(-5);
    }
    else if(personA.getNumber()<personB.getNumber())
    {
        personA.setMoney(-5);
        personB.setMoney(5);
    }

}

    if(personA.getMoney()>personB.getMoney())
    {
        cout<<"A win B lose"<<endl;
        cout<<"A win"<<personA.getMoney()<<endl;
    }
    else
    {
        cout<<"B win A lose"<<endl;
        cout<<"B win"<<personB.getMoney()<<endl;
    }

return 0;
}

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Kuihao 的頭像
    Kuihao

    溫暖午後的金針田__孕育有趣的創新

    Kuihao 發表在 痞客邦 留言(0) 人氣()