xin chào phần đa người.Mọi người có thể cho em hỏi gồm hàm như thế nào lấy một vài ngẫu nhiên trong 1 khoảng không. Ví dụ như em mong muốn lấy một số ngẫu nhiên từ 1 đến 13 thì sử dụng hàm ra sao. Em tìm kiếm trên mạng thì tất cả mỗi hàm rand(), mà lại nó không tồn tại giới hạn theo bản thân yêu cầu.Mong hầu hết người có thể giúp đỡ mang lại em


Bạn đang xem: Cách dùng hàm random trong c

Kết đúng theo phép phân chia lấy dựRandom 1 số trong tầm a đến b

int n = rand() % (b - a + 1) + a;Có thể áp dụng thêm hàm srand() trong tủ sách ctime nhằm random theo thời gian. Chứ k thì hàm rand() tắt đi random lại vẫn số cũ


viết 1 dòng class luôn:

#include #include #include class Randompublic: template static typename std::enable_if::value, T>::type range(T low, T high) std::uniform_int_distribution dist(low, high); return dist(prng); template static typename std::enable_if::value, T>::type range(T low, T high) std::uniform_real_distribution dist(low, high); return dist(prng); private: static std::mt19937 prng;;std::mt19937 Random::prngstd::chrono::high_resolution_clock::now().time_since_epoch().count();int main(){ for (int i = 0; i dài mẫu thế chứ xài thì cứ Random::range(a, b) là ngon lành, a, b thuộc kiểu, là số nguyên xuất xắc số thực gì rồi cũng chơi tuốt

*


Xem thêm:

hàm rng từ bỏ viết là sao? Là cung cấp (distribution) tự chọn đó hả? https://en.wikipedia.org/wiki/Inverse_transform_sampling Vọc demo nè: https://tritran.xyz/posts/random-voi-pdf-bat-ki/

còn thay cái prng mt19937 thì ko biết

*
muốn viết demo thì xem http://www.pcg-random.org/ coi bạn ta viết cầm cố nào, mà phải pass đủ một số loại test tỷ lệ lằng nhằng lắm
*


Không

*
cài điều này này
*
http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf

Paper của pcg thì cần đọc từ bỏ trang 25 trở đi, mà có vẻ phải hiểu từ từ.


http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator

hình như thỏa 4 đk là được rồi nè: gồm result_type, bao gồm min(), có max() cùng operator() sinh số ngẫu nhiên.

edit:

#include #include #include class MyHorribleRngpublic: using result_type = uint32_t; MyHorribleRng(result_type seed=1) : seedseed result_type min()const return 0; result_type max()const return 4294967295; result_type operator()() return seed = seed * 3; private: result_type seed;;int main(){ MyHorribleRng rng; std::uniform_int_distribution dist(0, 9); for (int i = 0; i được nè

*