问题描述
练习2-3 编写函数htoi(s),把由16进制数字组成的字符串(包含可选的前缀0X或0x)转换成与之等价的整形值。字符串中允许包含的数字包括:0 ~ 9, a ~ f,A ~ F。 Write the function htoi(s)
, which converts a string of hexadecimal digits (including an optional 0x
or 0X)
into its equivalent integer value. The allowable digits are 0
through 9,
a
through f,
and A
through F
.
解题思路
1.就是输入十六进制,输出十进制
2.首先写一个函数,把输入读入到一个数组中,我这里用我自己写的getlines实现,你也可以用for+scanf
3.要判断输入的是否是十六进制,字符串只能是0~9、a~f、A~F
4.转换公式:n = n * 16 + result;(后面详细接受这个公式什么意思,怎么推到来的)
代码如下
1 #include<stdio.h> 2 #define MAXLEN 1024 3 #define YES 1//是十六进制 4 #define NO 0//不是十六进制 5 6 int htoi(char array[]);//进制转换函数 7 int getlines(char array[],int maxlen);//字符串读取函数 8 9 int main() 10 { 11 int len;//字符串长度 12 int ten_number;//十进制数 13 char array[MAXLEN]; 14 while ((len = getlines(array,MAXLEN)) > 0) 15 { 16 ten_number = htoi(array); 17 printf("%d", ten_number); 18 putchar(' '); 19 } 20 return 0; 21 } 22 23 int getlines(char array[],int maxlen) 24 { 25 int c,i; 26 for (i = 0; i < maxlen-1 && (c = getchar())!=EOF && c!= ' '; i++) 27 { 28 array[i] = c; 29 } 30 if (c==' ') 31 { 32 array[i] = c; 33 i++; 34 } 35 array[i] = '