การสร้างเลขฐานสิบหกสุ่มใน C++
เราจะพูดถึงโปรแกรม C++ ที่สร้างเลขฐานสิบหกสุ่ม โดยใช้ฟังก์ชัน rand() และ itoa() มาดูรายละเอียดฟังก์ชันทั้งสอง
rand()
rand() เป็นฟังก์ชันกำหนดไว้ล่วงหน้าของ C++ ประกาศในเฮดเดอร์ <stdlib.h> ใช้สร้างตัวเลขสุ่มในช่วงที่กำหนด min_n คือค่าต่ำสุด max_n คือค่าสูงสุด rand() จะคืนค่าระหว่าง min_n ถึง (max_n - 1) รวมขอบเขต ตัวอย่าง ถ้ากำหนด 1 และ 100 จะได้ค่า 1 ถึง 99
itoa()
แปลงค่าทศนิยมหรือจำนวนเต็มเป็นสตริงที่จบด้วย null ตามฐานที่กำหนด เก็บผลลัพธ์ในอาเรย์ที่ผู้ใช้กำหนด
ไวยากรณ์
itoa(new_n, Hexadec_n, 16);
new_n = จำนวนเต็มสุ่ม, Hexadec_n = อาเรย์ผู้ใช้, 16 = ฐานสิบหก
อัลกอริทึม
Begin
max_n = 100, min_n = 1
อาเรย์ Hexadec_n แบบ char, ตัวแปร new_n, i
for i = 0 to 4
new_n = (rand() % (max_n + 1 - min_n)) + min_n
แสดง "The random number is:" และค่า new_n
เรียก itoa(new_n, Hexadec_n, 16) แปลงเป็นฐานสิบหก
แสดง "Equivalent Hex Byte:" และค่า Hexadec_n
End
ตัวอย่างโค้ด
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv) {
int max_n = 100, min_n = 1;
char Hexadec_n[100];
int new_n, i;
for (i = 0; i < 5; i++) {
new_n = ((rand() % (max_n + 1 - min_n)) + min_n);
cout << "The random number is: " << new_n;
itoa(new_n, Hexadec_n, 16);
cout << "\nEquivalent Hex Byte: " << Hexadec_n << endl << "\n";
}
return 0;
}
ผลลัพธ์
The random number is: 42 Equivalent Hex Byte: 2a The random number is: 68 Equivalent Hex Byte: 44 The random number is: 35 Equivalent Hex Byte: 23 The random number is: 1 Equivalent Hex Byte: 1 The random number is: 70 Equivalent Hex Byte: 46