~C++设计一个程序输入一个十进制数输出相应的十六进制数设计一个函数实现数制转换。用C++~~~~~~~~~~~~C++
代码文本:
char d[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
void convertDecimal2Hex(int num, char* szHex){
szHex[0]=d[(unsigned)(num&0x0000000F)];
szHex[1]=d[(unsigned)(num&0x000000F0>>1*4)];
szHex[2]=d[(unsigned)(num&0x00000F00>>2*4)];
szHex[3]=d[(unsigned)(num&0x0000F000>>3*4)];
szHex[4]=d[(unsigned)(num&0x000F0000>>4*4)];
szHex[5]=d[(unsigned)(num&0x00F00000>>5*4)];
szHex[6]=d[(unsigned)(num&0x0F000000>>6*4)];
szHex[7]=d[(unsigned)(num&0xF0000000>>7*4)];
szHex[8]='\0';
}
void main(){
char szHex[9];
convertDecimal2Hex(34555, szHex);
printf("%s", szHex);
}
思路如此,请自己测试,convertDecimal2Hex中的逻辑可以改为循环。
/*
36 : 24
78 : 4E
54 : 36
921 : 399
658 : 292
895 : 37F
458 : 1CA
963 : 3C3
264 : 108
225 : E1
159 : 9F
Press any key to continue
*/
#include <iostream.h>
char *Dec2Hex(char *hex,unsigned num) {
int i,n;
char ch;
for(n = 0; num; ++n) {
ch = num % 16;
if(ch > 9) hex[n] = ch - 10 + 'A';
else hex[n] = ch + '0';
num /= 16;
}
hex[n] = '\0';
for(i = 0; i < n/2; ++i) {
ch = hex[i];
hex[i] = hex[n - 1 - i];
hex[n - 1 - i] = ch;
}
return hex;
}
int main() {
int a[] = {36,78,54,921,658,895,458,963,264,225,159};
int i,n = sizeof(a)/sizeof(a[0]);
char s[10];
for(i = 0; i < n; ++i) {
cout.width(4);
cout << a[i] << " : " << Dec2Hex(s,a[i]) << endl;
}
return 0;
}
的,,
C++ 程序
专业。