1.题目要求
2.代码实现
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int hexToDec(char hex[]) {
int len = strlen(hex);
int base = 1;
int dec = 0;
for (int i = len - 1; i >= 0; i--) {
if (isdigit(hex[i])) {
dec += (hex[i] - '0') * base;
} else if (isalpha(hex[i])) {
dec += (toupper(hex[i]) - 'A' + 10) * base;
}
base *= 16;
}
return dec;
}
int main() {
char input[80];
printf("请输入十六进制字符串:");
scanf("%s", input);
char hexStr[80];
int j = 0;
for (int i = 0; i < strlen(input); i++) {
if ((input[i] >= '0' && input[i] <= '9') ||
(input[i] >= 'a' && input[i] <= 'f') ||
(input[i] >= 'A' && input[i] <= 'F')) {
hexStr[j++] = input[i];
}
}
hexStr[j] = '\0';
int decimal = hexToDec(hexStr);
printf("十六进制串%s的值=十进制%.0f", hexStr, (float)decimal);
return 0;
}
3.代码详解