首页 > 解决方案 > 十六进制到十进制转换器不起作用(c ++)

问题描述

因此,作为作业的一部分,我编写了一个将十六进制转换为十进制的程序。但我无法得到想要的结果。有人可以指出此代码中的错误吗?

#include<bits/stdc++.h>
#include<math.h>
using namespace std;

int hexaToDecimal(string n){
    int ans = 0;
    int power =1;
    int s = n.size();

    for(int i=s-1; i>=0; i--){
        if(n[i] >= '0' && n[i] <= '9'){
            ans = ans + power*(n[i]);
        }
        else if(n[i] >= 'A' && n[i] <= 'F'){
            ans = ans + power*(n[i]-'A' + 10);
        }
        power = power * 16;
    }
    return ans;
}

        


int main(){
    string n;
    cin>>n;
    cout<<hexaToDecimal(n)<<endl;
    return 0;
}

标签: c++hex

解决方案


更简单的方法:

unsigned fromHex(const string &s) { 
    unsigned result = 0;
    for (char c : s) 
        result = result << 4 | hexDigit(c);
    return result;
}

unsigned hexDigit(char c) { 
    return c > ‘9’ ? c - ‘A’ + 10: c - ‘0’;
}

推荐阅读