【问题标题】:Hexadecimal addition C++十六进制加法 C++
【发布时间】:2014-10-06 19:13:29
【问题描述】:

我需要编写一个程序来读取两个十六进制数字,将它们转换为十进制形式,并以十进制打印出两个数字的总和。据我所知,我似乎无法获得正确的值来加起来。

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

【问题讨论】:

标签: c++ hex


【解决方案1】:

试试这个:

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

【讨论】:

  • 感谢 Rustam,但不完全是我需要的。该程序基本上需要读取两组十六进制值(e.i 45AF,12B3)并将它们转换为十进制形式,然后将这些值相加并打印结果。
  • 然后从 'cout' 行中删除 'hex' 并检查
【解决方案2】:

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

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

【讨论】:

  • 转换函数是否返回任何值是否重要?例如,可以在参数列表中将它们称为 void 吗?
  • 您可以通过传递引用使转换函数不返回任何内容(void),但您为什么要这样做?
猜你喜欢
  • 2011-06-01
  • 2012-05-27
  • 2016-08-01
  • 2011-12-09
  • 2014-04-18
  • 2014-11-30
  • 2014-07-03
  • 2015-02-14
  • 2018-11-18
相关资源
最近更新 更多