C++程式生成隨機十六進位制位元組
我們將討論一個可以生成隨機十六進位制數的C++程式。在這裡,我們將使用rand()和itoa()函式來實現它。讓我們分別並分類地討論這些函式。
rand(): rand()函式是C++的預定義方法。它在<stdlib.h>標頭檔案中宣告。rand()用於在一定範圍內生成隨機數。這裡min_n是隨機數的最小範圍,max_n是數字的最大範圍。因此,rand()將返回min_n到(max_n – 1)之間的隨機數,包括限制值。如果我們將下限和上限分別設定為1和100,則rand()將返回1到(100 – 1)的值。即從1到99。
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
廣告