C++生成隨機數

十一的杂文录發表於2024-04-12

C++11 標準

#include <iostream>
#include <random>
using namespace std;

int main()
{
    cout << "C++11" << endl;

    default_random_engine random(time(nullptr));

    uniform_int_distribution<int> random_num1(1, 10000);        // 整數隨機數
    uniform_real_distribution<float> random_num2(1.0, 10000.0); // 浮點數隨機數

    // 列印隨機整數
    cout << "隨機數,整數: ";
    for (int i = 0; i < 10; i++)
    {
        cout << random_num1(random) << "  ";
    }
    cout << endl;

    // 列印隨機浮點數
    cout << "隨機數,浮點數: ";
    for (int i = 0; i < 10; i++)
    {
        cout << random_num2(random) << "  ";
    }
    cout << endl;

    return 0;
}

相關文章