2011/04/01

亂數

#include <cstdlib>
#include <iostream>
#include <time.h>

using namespace std;

int main(int argc, char *argv[])
{
    bool Find = false;
    int A,B;//表示範圍的起始與結束 
    int Change;
    int Num;
    int Temp;
    int Index = 0;

    srand(time(NULL));

    cout << "請輸入範圍起始值:";
    cin >> A;
    cout << "請輸入範圍結束值:";
    cin >> B;
    
    if(A>B)
    {
        Change = A;
        A = B;
        B = Change;
    }
    
    cout << "請輸入亂數個數:";
    cin >> Num;

    int Box[Num];

    for(int i=0; i<Num; i++)
    {
        Box[i] = 0;
    }
    Box[Num-1] = -1;

    while(Box[Num-1] == -1)
    {
        Find = false;//此處旗標需重新設定為false! 
        Temp = rand()%B+A;
        for(int j=0; j<Num; j++)
        {
            if(Box[j] == Temp)
            {
                Find = true;
                break;
            }
        }
        //
        if(!Find)
        {
            Box[Index] = Temp;
            Index++;
        }
    }
    //輸出產生的亂數 
    cout << "產生的亂數:" << endl;

    for(int k=0; k<Num; k++)
    {
        cout << Box[k] << " ";
    }

    cout << endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}