เราจะหารือเกี่ยวกับโปรแกรม C ++ ซึ่งสามารถสร้างเลขฐานสิบหกแบบสุ่มได้ ที่นี่เราจะใช้ฟังก์ชัน rand() และ itoa() เพื่อใช้งานเหมือนกัน ให้เราหารือเกี่ยวกับฟังก์ชันเหล่านี้แยกกันและตามหมวดหมู่
แรนด์(): ฟังก์ชัน rand() เป็นวิธีการที่กำหนดไว้ล่วงหน้าของ C++ มันถูกประกาศในไฟล์ส่วนหัว
itoa(): ส่งกลับค่าที่แปลงแล้วของตัวเลขทศนิยมหรือจำนวนเต็ม มันแปลงค่าเป็นสตริงที่สิ้นสุดด้วยค่า null ด้วยฐานที่ระบุ มันเก็บค่าที่แปลงเป็นอาร์เรย์ที่ผู้ใช้กำหนด
ไวยากรณ์
itoa(new_n, Hexadec_n, 16);
โดยที่ new_n คือเลขจำนวนเต็มสุ่มใดๆ และ Hexadec_n คืออาร์เรย์ที่ผู้ใช้กำหนดและ 16 เป็นฐานของเลขฐานสิบหก นั่นหมายถึงการแปลงเลขฐานสิบหรือจำนวนเต็มเป็นเลขฐานสิบหก
อัลกอริทึม
Begin Declare max_n to the integer datatype. Initialize max_n = 100. Declare min_n to the integer datatype. Initialize min_n = 1. Declare an array Hexadec_n to the character datatype. Declare new_n to the integer datatype. Declare i to the integer datatype. for (i = 0; i < 5; i++) new_n = ((rand() % (max_n + 1 - min_n)) + min_n) Print “The random number is:”. Print the value of new_n. Call itoa(new_n, Hexadec_n, 16) method to convert a random decimal number to hexadecimal number. Print “Equivalent Hex Byte:” Print the value of Hexadec_n. End.
ตัวอย่าง
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main(int argc, char **argv) {
int max_n = 100;
int min_n = 1;
char Hexadec_n[100];
int new_n;
int i;
for (i = 0; i < 5; i++) {
new_n = ((rand() % (max_n + 1 - min_n)) + min_n);
//rand() returns random decimal number.
cout<<"The random number is: "<<new_n;
itoa(new_n, Hexadec_n, 16); //converts decimal number to Hexadecimal number.
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