简体   繁体   English

十六进制到十进制转换器不起作用(C++)

[英]Hexadecimal to decimal converter not working (c++)

So, as part of an assignment, I wrote a program to convert hexadecimal to decimal.因此,作为作业的一部分,我编写了一个将十六进制转换为十进制的程序。 But I was not able to get the desired result.但是我没能得到想要的结果。 Can someone please pin point the error in this code?有人可以指出此代码中的错误吗?

#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;
}

Simpler way to go about it:更简单的方法:

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’;
}

You may add - '0' like - 'A' .您可以添加- '0'- 'A' There is the code:有代码:

#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] - '0'); //THERE.
        }
        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;
}

Changes only near //THERE.仅在//THERE.附近更改//THERE.

Here is a different approach on how to solve your problem.这是关于如何解决您的问题的不同方法。 You could use std::hex which is defined in the headerfile #include<iostream> Which is a simpler way to do it.您可以使用在头文件#include<iostream>定义的std::hex ,这是一种更简单的方法。

For Example:例如:

#include <iostream>


int main()
{
    int HexNum;
    std::cin >> std::hex >> HexNum;
    std::cout << HexNum << std::endl;

    return 0;
}

Output:输出:

10F
271

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM