ให้เราดูวิธีการสร้างตัวเลขสุ่มที่แตกต่างกันโดยใช้ C ++ ที่นี่เรากำลังสร้างตัวเลขสุ่มในช่วง 0 ถึงค่าบางค่า (ในโปรแกรมนี้ ค่าสูงสุดคือ 100)
ในการดำเนินการนี้ เราใช้ฟังก์ชัน srand() นี่อยู่ในไลบรารี C++ ฟังก์ชัน void srand(unsigned int seed) เมล็ดเครื่องกำเนิดตัวเลขสุ่มที่ใช้โดยฟังก์ชัน แรนด์ .
การประกาศของ srand() จะเป็นดังนี้ −
void srand(unsigned int seed)
มันใช้พารามิเตอร์ที่เรียกว่าเมล็ด นี่คือค่าจำนวนเต็มที่จะใช้เป็นเมล็ดโดยอัลกอริธึมตัวสร้างตัวเลขสุ่มหลอก ฟังก์ชันนี้ไม่ส่งคืนสิ่งใด
เพื่อให้ได้ตัวเลขเราต้องใช้วิธี rand() เพื่อให้ได้ตัวเลขที่อยู่ในช่วง 0 ถึงสูงสุด เราใช้ตัวดำเนินการโมดูลัสเพื่อหาค่าเศษเหลือ
สำหรับค่า seed เรากำลังระบุผลลัพธ์ของฟังก์ชัน time(0) ลงในฟังก์ชัน srand()
ตัวอย่าง
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
main() {
int max;
max = 100; //set the upper bound to generate the random number
srand(time(0));
for(int i = 0; i<10; i++) { //generate 10 random numbers
cout << "The random number is: "<<rand()%max << endl;
}
} ผลลัพธ์
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