Hướng dẫn tạo số ngẫu nhiên khác nhau trong C++. Ở đây tạo số trong khoảng 0 đến giá trị max (ví dụ 100).
Sử dụng hàm srand() từ thư viện C++. Khai báo: void srand(unsigned int seed) khởi tạo bộ sinh số ngẫu nhiên cho hàm rand().
Tham số seed là giá trị nguyên để khởi tạo thuật toán giả ngẫu nhiên. Hàm không trả về giá trị.
Để lấy số trong khoảng 0 đến max, dùng toán tử modulus với rand(). 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));
for (int i = 0; i < 10; i++) {
cout << "The random number is: " << rand() % max << endl;
}
return 0;
}
Kết quả
The random number is: 6 The random number is: 82 The random number is: 51 The random number is: 46 The random number is: 97 The random number is: 60 The random number is: 20 The random number is: 2 The random number is: 55 The random number is: 91