编写函数int conv(char hex[])将16进制的数字字符串转换为十进制整数,要求主函数中输入16进制数字字符串,调用conv函数输出其十进制整数。16进制数字字符串的位数要求在6位以下,1位以上,并以H或h结尾。 请只提供子函数的编写。 【样例输入】 57ABH 【样例输出】 22443 #include <stdio.h> #include <stdlib.h> int conv(char hex[]); int main() { int m; char hex[7]; scanf("%s",hex); m=conv(hex); if(m==-1) printf("输入有误!"); else printf("%d\n",m); }
时间: 2023-12-06 18:43:28 浏览: 62
int conv(char hex[]) {
int i, len, result = 0;
len = strlen(hex); // 获取字符串长度
if (hex[len-1] == 'H' || hex[len-1] == 'h') { // 判断最后一位是否为 H 或 h
for (i = 0; i < len-1; i++) { // 遍历字符串
if (hex[i] >= '0' && hex[i] <= '9') { // 如果是数字字符
result = result * 16 + (hex[i] - '0'); // 转换为对应的十进制数并加到结果中
} else if (hex[i] >= 'A' && hex[i] <= 'F') { // 如果是大写字母
result = result * 16 + (hex[i] - 'A' + 10); // 转换为对应的十进制数并加到结果中
} else if (hex[i] >= 'a' && hex[i] <= 'f') { // 如果是小写字母
result = result * 16 + (hex[i] - 'a' + 10); // 转换为对应的十进制数并加到结果中
} else { // 如果是其他字符,说明输入有误,返回 -1
return -1;
}
}
return result;
} else { // 如果最后一位不是 H 或 h,说明输入有误,返回 -1
return -1;
}
}
阅读全文
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)