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