練習2-3,編寫函數htoi(s),把十六進制的字符串轉換爲整數值。
#include <stdio.h> #include <string.h> #include <math.h> #include <ctype.h> //測試用函數 int htoi(char s[]); // 函數原型 main() { printf("%d\n", htoi("0xffff")); } int htoi(char s[]) { int c = 0; int i = strlen(s) - 1; int copy_i = i; int di = 0; while (s[i] != 'x' && di <= copy_i) { if (isdigit(s[i])) c += (int)(s[i]) * pow(16, di); else c += ((tolower((int)(s[i])) - 87) * pow(16, di)); \\發現不是數字,轉換爲16進制值 i--; \\是i減減 di++; } return c; }
用gcc編譯時要在末尾加上 -lm 選項,鏈接數學庫,否則pow函數會報錯。