หากเรากำลังสร้างตัวเลขสุ่มในโปรแกรม จำเป็นต้องควบคุมชุดตัวเลข
สุ่ม() และ srand() ฟังก์ชันต่างๆ ใช้สำหรับสร้างตัวสร้างตัวเลขสุ่ม
กระบวนการกำหนดหมายเลขเริ่มต้นของตัวสร้างตัวเลขสุ่มเรียกว่าการเพาะตัวสร้าง
-
randomize() ใช้นาฬิกาของพีซีเพื่อสร้างเมล็ดสุ่ม
-
srand() ช่วยให้เราสามารถระบุค่าเริ่มต้นของเครื่องกำเนิดตัวเลขสุ่มได้
โปรแกรม
รับด้านล่างเป็นโปรแกรม C บนแรนด์ -
#include<stdio.h>
int main(){
// create same sequence of
// random numbers on every time the program runs
for(int i = 0; i<10; i++)
printf(" %d ", rand());
return 0;
} ผลลัพธ์
คุณจะเห็นผลลัพธ์ต่อไปนี้ -
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421
ต่อไปนี้เป็นโปรแกรม C บน srand -
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int main(){
// create different sequence of
// random numbers on every time the program runs
// It Use current time as seed for random generator
srand(time(0));
for(int i = 0; i<10; i++)
printf(" %d ", rand());
return 0;
} ผลลัพธ์
คุณจะเห็นผลลัพธ์ต่อไปนี้ -
1919778910 1203408690 1755813469 1976428341 37040990 1849384103 986990763 2040061815 391541163 1718314135