题目描述 写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 ) 输入描述: 输入一个十六进制的数值字符串。 输出描述: 输出该数值的十进制字符串。
解法1(C):
#include<stdio.h>
#include<string.h>
int hex2dec(char hex)
{
if (hex >= '0' && hex <= '9')
return hex - '0';
else if (hex >= 'A' && hex <= 'F')
return hex - 'A' + 10;
else
return -1;
}
char* dec2str(int dec)
{
int i, j;
char str[100] = { 0 };
char restr[100] = { 0 };
i = 0;
do
{
restr[i++] = dec % 10 + '0';
dec /= 10;
} while (dec);
j = 0;
i = i - 1;
while (i >= 0)
str[j++] = restr[i--];
return str;
}
int main()
{
char instr[100] = { 0 };
int len, dec, tmp, atom, i;
while (fgets(instr, 100, stdin))
{
dec = 0;
atom = 1;
len = strlen(instr);
for (i = len - 2; i > 1; --i)
{
tmp = hex2dec(instr[i]);
dec += (int)(tmp * atom);
atom *= 16;
}
printf("%s\n", dec2str(dec));
memset(instr, 0, 100);
}
return 0;
}
解法2(Python3):
while True:
try:
print(str(int(input(), 16)))
except:
break