mercredi 31 mars 2021

Why it is throwing wrong answers?? Hexadecimal to decimal conversion problem

Please help me to identify the error in this program, as for me it's looking correct,I have checked it,but it is giving wrong answers. In this program I have checked explicitly for A,B,C,D,E,F,and according to them their respective values.

#include<iostream>
#include<cmath>
#include<bits/stdc++.h>
using namespace std;
void convert(string num)
{
   long int last_digit;
    int s=num.length();
    int i;
    long long int result=0;
    reverse(num.begin(),num.end());                 
    for(i=0;i<s;i++)
    {
        if(num[i]=='a' || num[i]=='A')
        {
            last_digit=10;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='b'|| num[i]=='B')
        {
            last_digit=11;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='c' || num[i]=='C')
        {
            last_digit=12;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='d'|| num[i]=='D' )
        {
            last_digit=13;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='e'|| num[i]=='E' )
        {
            last_digit=14;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='f' || num[i]=='F')
        {
            last_digit=15;
            result+=last_digit*pow(16,i);
        }
        else {
            last_digit=num[i];
        result+=last_digit*pow(16,i);
        }
    }
    cout<<result;
}
int main()
{
    string hexa;
    cout<<"Enter the hexadecimal number:";
    getline(cin,hexa);
    convert(hexa);
}

Aucun commentaire:

Enregistrer un commentaire