用函数,输入十六进制数,输出相应的十进制?
#include <stdio.h>int main(void) {
int n;
scanf("%x", &n);
printf("%d\n", n);
return 0;
}
除了上述方法外,还有什么办法,请赐教
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> void syntax_error(char reason) { printf("Syntax error: \'%c\'(Must be \'0\' to \'9\' or \'a/A\' to \'f/F\')\nProgram will to exit.\n", reason); system("pause"); exit(1); } int main(void) { char hex[12], * p1 = hex, * p2 = hex; int dec = 0, negative = 0, digit = 1; scanf("%s", hex); if (*p1 == '0' && (*(p1 + 1) == 'x' || *(p1 + 1) == 'X')) p1 += 2; if (*p1 == '-') { negative = 1; p1++; } p2 += strlen(hex) - 1; while (p2 >= p1) { if (*p2 >= '0' && *p2 <= '9') dec += (*p2 - '0') * digit; else if((*p2 >= 'a' && *p2 <= 'f') || (*p2 >= 'A' && *p2 <= 'F')) isupper(*p2) ? (dec += (*p2 - 'A' + 10) * digit) : (dec += (*p2 - 'a' + 10) * digit); else syntax_error(*p2); digit *= 16; p2--; } if (negative) dec = -dec; printf("%d\n", dec); system("pause"); return 0; }输入负数:-ff 或 0x-ff都可以。