c++ rand 随机数

创建日期: 2024-06-11 19:12 | 作者: 风波 | 浏览次数: 17 | 分类: C++

来源:https://en.cppreference.com/w/cpp/numeric/random/rand

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

int main() 
{
    std::srand(std::time(nullptr)); // use current time as seed for random generator
    int random_value = std::rand();
    std::cout << "Random value on [0, " << RAND_MAX << "]: " << random_value << '\n';

    for (const int times = 8; const int sides : {2, 4, 6, 8})
    {
        std::cout << "Roll " << sides << "-sided dice " << times << " times: ";
        for (int n = 0; n != times; ++n)
        {
            int x = sides + 1;
            while (x > sides) 
                x = 1 + std::rand() / ((RAND_MAX + 1u) / sides); 
                    // Note: 1 + rand() % sides is biased
            std::cout << x << ' ';
        }
        std::cout << '\n';
    }
}
17 浏览
13 爬虫
0 评论