เราจะมาดูวิธีการสร้างตัวเลขสุ่มในช่วงที่กำหนดโดยใช้ C เพื่อแก้ปัญหานี้ เราจะใช้ฟังก์ชัน srand() เวลาปัจจุบันจะถูกใช้เพื่อ seed ฟังก์ชัน srad()
ฟังก์ชันนี้ไม่สามารถสร้างตัวเลขสุ่มในช่วงใดๆ ได้ แต่สามารถสร้างตัวเลขระหว่าง 0 ถึงค่าบางค่าได้ ดังนั้นสำหรับเรื่องนี้ เราต้องทำตามหนึ่งเคล็ดลับ เราจะสร้างตัวเลขสุ่มระหว่าง 0 ถึง (บน – ล่าง + 1) จากนั้นเพิ่มขีดจำกัดล่างสำหรับการออฟเซ็ต
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random(int l, int r, int count) { //this will generate random number in range l and r
int i;
for (i = 0; i < count; i++) {
int rand_num = (rand() % (r - l + 1)) + l;
printf("%d ", rand_num);
}
}
main() {
int lower = 10, upper = 15, count = 15;
srand(time(0)); //current time as seed of random number generator
generate_random(lower, upper, count);
printf("\n");
} ผลลัพธ์
15 11 13 10 13 10 15 11 14 12 12 13 12 13 14