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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP