實作C++亂數的使用
範例是用樂透彩,由電腦亂數取出每一組有6個數字(不重複)的序列並印出
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
    int a,n;
    int Index = 0;
    int Box[6];
    bool Exist ;
    srand(time(NULL));
    cout << "Please input a number:";
    cin >> n;
    while(n > 0)
    {
        for(int i=0; i<6; i++)
        {
            a = rand()%49+1;
            Exist = false;
            for(int j=0; j<Index; j++)
            {
                if(Box[j] == a)
                {
                    Exist = true;
                    break;
                }
            }
            if(Exist == false)
            {
                Box[Index] = a;
                Index++;
            }
            else
            {
                i--;
            }
        }
        for(int i=0; i<6; i++)
        {
            if(Box[i] < 10)
            {
                cout << 0 << Box[i] << " ";
            }
            else
            {
                cout << Box[i] << " ";
            }
        }
        cout << endl;
        n--;
        Index = 0;
    }
    system("PAUSE");
    return 0;
}
 
沒有留言:
張貼留言