บทนำ
มาดูวิธีสร้างเลขสุ่มใน C++ ที่นี่เราสร้างเลขสุ่มในช่วง 0 ถึงค่าสูงสุด (ในโปรแกรมนี้คือ 100)
การใช้งาน srand()
ใช้ฟังก์ชัน srand() จากไลบรารี C ฟังก์ชัน void srand(unsigned int seed) ใช้ seed ให้กับตัวสร้างเลขสุ่มที่ใช้โดย rand()
void srand(unsigned int seed)
รับพารามิเตอร์ seed เป็นค่าจำนวนเต็มสำหรับอัลกอริทึมสุ่มเทียม ฟังก์ชันนี้ไม่คืนค่า
ใช้ rand() เพื่อรับเลขสุ่ม ใช้ modulus operator เพื่อให้ได้เลขในช่วง 0 ถึง max
สำหรับ seed ใช้ผลลัพธ์ของ time(0) ใส่ใน srand()
ตัวอย่างโค้ด
#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;
}
ผลลัพธ์ตัวอย่าง
The random number is: 51
The random number is: 29
The random number is: 47