Hướng dẫn sinh số ngẫu nhiên trong C++. Sinh số trong khoảng 0 đến max (ví dụ 100).
Sử dụng srand() từ thư viện C. Khai báo: void srand(unsigned int seed). Tham số seed khởi tạo thuật toán giả ngẫu nhiên. Dùng rand() và toán tử modulus để giới hạn phạm vi. Seed thường dùng time(0).
Ví dụ
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int max = 100;
srand(time(0));
cout << "The random number is: " << rand() % max;
return 0;
}
Kết quả (mẫu)
The random number is: 51
The random number is: 29
The random number is: 47