一、题目描述

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )

二、解题思路

  • 逐个读取字符串的字符,进行变换
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void sln(string str)
{
   
    auto len = str.size();
    long long sln = 0;
    for (size_t i = 2; i < len; i++)
    {
   
        unsigned short tmp;
        if (str[i] >= 'a' && str[i] <= 'f')
        {
   
            tmp = str[i] - 'a' + 10;
        }
        else if (str[i] >= 'A' && str[i] <= 'F')
            tmp = str[i] - 'A' + 10;
        else if (str[i] >= '0' && str[i] <= '9')
            tmp = str[i] - '0';
        else
        {
   
            cout << "Error!" << endl;
            return;
        }
        sln = sln * 16 + tmp;
    }
    cout << sln << endl;
}
int main()
{
   
    string str;
    while (cin >> str)
    {
   
        sln(str);
    }
    return 0;
}
  • 使用C++的输入输出进制方法
#include <iostream>
using namespace std;

int main()
{
   
    int a;
    while(cin>>hex>>a){
   
    cout<<a<<endl;
    }
}