十六进制加法C ++

时间:2014-10-06 19:13:30

标签: c++ hex

我需要编写一个读取两个十六进制数字的程序,将它们转换为十进制形式,并以十进制形式输出两个数字的总和。这是我已经得到的,我似乎无法得到正确的值加起来。

 #include <iostream>
#include <iomanip>

using namespace std;
void Hex_to_Dec(char &, char &);
int main()
{
    char hex1;
    char hex2;

    cout << " Please enter a hexadecimal number: " << endl;
    cin >> hex1;

    cout << " Please enter another hexadecimal value: " << endl;
    cin >> hex2;

    Hex_to_Dec(hex1, hex2);

    cout << "The decimal sum of" << hex1 << " and " << hex2 << " is " << hex1 + hex2 << endl;

    return 0;
}

void Hex_to_Dec(char & hex1, char & hex2)
{
    std::cin >> std::hex >> hex1;
    std::cout << hex1 << std::endl;

    std::cin >> std::hex >> hex2;
    std::cout << hex2 << std::endl;
}

2 个答案:

答案 0 :(得分:0)

如果您必须编写自己的算法以从十六进制转换为十进制,反之亦然,那么我建议您使用以下粗略模板:

#include <iostream>
#include <string>

using namespace std;

int hexToDecimal(string);
string decimalToHex(int);

int main()
{
    cout << "Enter a hex number: ";
    string hex1;
    cin >> hex1;

    cout << "Enter a hex number: ";
    string hex2;
    cin >> hex2;

    cout << "The sum of the numbers in hex is: ";
    cout << decimalToHex(hexToDecimal(hex1) + hexToDecimal(hex2));

    return 0;
}

int hexToDecimal(string hex)
{
    // Code here.
}

string decimalToHex(int decimal)
{
    // Code here.
}

答案 1 :(得分:0)

试试这个:

   int main(){

    int hex1;
    int hex2;
    cout << " Please enter a hexadecimal number: ";
    cin>>hex>>hex1;
    cout << " Please enter another hexadecimal value: ";
    cin>>hex>>hex2;
    cout<<"The decimal sum of  "<<hex1<<" and  "<<hex2<<" = "<<(hex1+hex2) ;
    return 0;
}