Skip to content
Rain Hu's Workspace
Go back

[C++] 如何產生 random 值

Rain Hu

rand() 函數

C-style

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    srand(time(NULL));      // random seed
    int x = rand();

    printf("x = %d\n", x);
    return 0;
}

Cpp-style

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    srand(time(NULL));
    int x = rand();

    cout << "x = " << x << endl;
    cout << "x is between 0 and " << RAND_MAX << endl;

    return 0;
}

亂數種子

固定亂數種子

[0, 1) 浮點數亂數

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    srand(time(NULL));
    double x = (double)rand()/(RAND_MAX + 1.0);

    cout << "x = " << x << endl;

    return 0;
}

[a, b)特定範圍浮點數亂數

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    srand(time(NULL));
    double x = (double)rand()/(RAND_MAX + 1.0);

    cout << "x = " << x << endl;

    return 0;
}

[a, b)特定範圍整數亂數

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    srand(time(NULL));

    int a = 1;    // min
    int b = 100;  // max

    int x = rand() % (b - a + 1) + a;

    cout << "x = " << x << endl;

    return 0;
}

均勻分布亂數(uniform distribution)

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int randint(int n){
    if ((n - 1) == RAND_MAX)
        return rand();
    long end = RAND_MAX / n;
    assert (end > 0L);
    end *= n;
    int r;
    while ((r = rand()) >= end);

    return r % n;
}

int main(){
    int x = randint(5);
    cout << x << endl;
}

使用 randint 函數產生特定範圍整數亂數:

int x = randint(max - min + 1) + min;

Share this post on:

Previous
[IDAS+] Optimize Summary Table Function
Next
[C++] Cout functions