C语言,请帮我写一个16进制转10进制的代码
时间: 2024-05-02 15:21:31 浏览: 14
以下是一个简单的16进制转10进制的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
char hex_num[10];
int dec_num = 0;
int i, len;
// 读取16进制数字
printf("请输入一个16进制数:");
scanf("%s", hex_num);
// 计算16进制数的长度
len = strlen(hex_num);
// 将16进制数字转换为10进制数字
for (i = 0; hex_num[i]!='\0'; i++) {
if (hex_num[i]>='0' && hex_num[i]<='9') {
dec_num += (hex_num[i] - '0') * pow(16, len-1);
len--;
}
else if (hex_num[i]>='a' && hex_num[i]<='f') {
dec_num += (hex_num[i] - 'a' + 10) * pow(16, len-1);
len--;
}
else if (hex_num[i]>='A' && hex_num[i]<='F') {
dec_num += (hex_num[i] - 'A' + 10) * pow(16, len-1);
len--;
}
else {
printf("输入的不是16进制数!\n");
exit(0);
}
}
// 输出10进制数字
printf("对应的10进制数为:%d\n", dec_num);
return 0;
}
```
代码逻辑大致如下:
1. 读取用户输入的16进制数字,存储到字符数组 `hex_num` 中。
2. 计算 `hex_num` 的长度,以便于后续计算。
3. 遍历 `hex_num` 中的每一位,根据其所处的范围(0-9, a-f, A-F)计算其对应的10进制值,并加入到 `dec_num` 中。
4. 如果发现输入的字符不是16进制数字,则输出提示信息并退出程序。
5. 输出计算出的10进制数字 `dec_num`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)