编写一个函数,将一个十六进制数转换成十进制数,并写一个主函数测试这个函数写的是否正确。用c++写
时间: 2024-05-25 11:18:20 浏览: 11
#include <stdio.h>
#include <string.h>
#include <math.h>
int hexToDec(char hex[]);
int main()
{
char hex[20];
printf("Enter a hexadecimal number: ");
scanf("%s", hex);
printf("Decimal equivalent of %s is %d", hex, hexToDec(hex));
return 0;
}
int hexToDec(char hex[])
{
int len = strlen(hex);
int base = 1;
int dec = 0;
for (int i = len - 1; i >= 0; i--)
{
if (hex[i] >= '0' && hex[i] <= '9')
{
dec += (hex[i] - 48) * base;
base *= 16;
}
else if (hex[i] >= 'A' && hex[i] <= 'F')
{
dec += (hex[i] - 55) * base;
base *= 16;
}
else if (hex[i] >= 'a' && hex[i] <= 'f')
{
dec += (hex[i] - 87) * base;
base *= 16;
}
}
return dec;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)