rand() สร้าง Pseudorandom Number srand() ตั้ง Seed ให้ Random Generator
ตัวอย่าง: Seed คงที่ (ผลลัพธ์เดิมทุกครั้ง)
#include <iostream>
#include <cstdlib>
int main() {
srand(1); // Fixed Seed
for (int i = 0; i < 5; i++)
cout << rand() % 100 << " ";
return 0;
}
83 86 77 15 93
ตัวอย่าง: Seed จากเวลา (ผลลัพธ์ต่างทุกครั้ง)
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(NULL)); // Seed จากเวลาปัจจุบัน
for (int i = 0; i < 5; i++)
cout << rand() % 100 << " ";
return 0;
}
Run 1
63 98 17 49 46
Run 2
44 21 19 2 83
C++11 Modern Random (แนะนำ)
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 gen(rd()); // Mersenne Twister Engine
std::uniform_int_distribution<> dis(1, 100); // Range 1-100
for (int i = 0; i < 5; i++)
std::cout << dis(gen) << " ";
return 0;
}
ข้อได้เปรียบของ <random>
- Distribution ดีกว่า (Uniform, Normal, Poisson, ฯลฯ)
- Engine เลือกได้ (mt19937, minstd_rand, ฯลฯ)
- Thread-safe
- Quality สูงกว่า rand() มาก
อย่าใช้ rand() ใน Production Code ใช้ <random> แทน