早教吧 育儿知识 作业答案 考试题库 百科 知识分享

把16进制数对应的字符串转换成整数写函数inthtoi(chars[]),将字符串s,转换为整数,其中s为16进制数对应的字符串,例如“0x2f”,其中0x为16进制的前缀。C语言

题目详情
把16进制数对应的字符串转换成整数
写函数int htoi(char s[]),将字符串s,转换为整数,其中s为16进制数对应的字符串,例如“0x2f”,其中0x为16进制的前缀。C语言
▼优质解答
答案和解析
#include#include#include#define MAX 10
int htoi(char s[]){ //先统计位数,除去0,1“表示0x” int count = -1; for(count = 2;s[count]!='\0';++count); count-=2; int sum=0; int temp=0; //开始计数 for(int i=2;i<=count+1;++i) { switch(s[i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':temp = s[i]-48;break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':temp=s[i]-87;break; }
sum+=(pow(16.0,count-(i-2)-1)*temp); } return sum;}void main(){ char string[MAX]; printf("输入一个十六进制字符串:"); gets(string); printf("%s转换结果:%d",string,htoi(string)); system("pause");}