問題描述:輸入一個十六進制的字符串,輸出其對應的十進制整數
編譯環境:vc++6.0
代碼:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*輸入一個十六進制的字符串,輸出其對應的十進制整數*/
//方法:按位乘權相加
int converts(char* str)
{
char* p = str;
static int sum = 0, len=0; //len記錄十六進制的長度
while (*p) //將指針移到最‘\0’的位置
p++,len++;
p = str;//指針復位;指向str開頭
do
{
if (*p >= '0' && *p <= '9')
sum +=(int) ((*p-'0') * pow(16, (len--) - 1));
else if (*p >= 'A' && *p <= 'F')
sum += (int)((*p - 'A' + 10)* pow(16, (len--) - 1));
else //十六進制數不規範
exit(0);
p++;
} while (*p);
return sum;
}
int main()
{
char str[81];
printf("請輸入一個十六進制數:\n");
scanf("%s", str);
printf("\n對應的十進制數是:%d\n", converts(str));
return 0;
}
測試案例: