C++十六进制计算器运行时错误

C++ Hexadecimal calculator run time error

本文关键字:运行时错误 计算器 十六进制 C++      更新时间:2023-10-16

我正在努力让这件事正常工作,但我就是做不到。例如,它添加了像F+F=0000000001E这样的十六进制(我认为这是正确的,对吧?),但如果我在输入第一个十进制数(1D)后尝试添加1D+1D,它不允许我输入第二个十进制数,并输出总和为000000002E。

#include <iostream>
using namespace std;
void output(char number[]);
void hex_sum(char hex1[], char hex2[], char sum[]);
int main()
{
  char answer;
  do
    {
      char hex1[10] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
      char hex2[10] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
      char sum[10] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
      cout << "Enter the first hexadecimal number: n";
      cin >> hex1[0];
      cout << "Enter the second hexadecimal number: n";
      cin >> hex2[0];
      hex_sum(hex1, hex2, sum);
      cout << "The sum is: n";
      for(int i = 9; i >=0; i--)
    {
      cout << sum[i];
    }
      cout << "n" << "Would you like to try again? (Y/N)?n";
      cin >> answer;
    } while(answer == 'Y' || answer == 'y');
    cout << "Good-bye! n";
    return 0;
}
void hex_sum(char hex1[], char hex2[], char sum[])
{
  int x, y;
  int carry = 0;
  int other_carry = 0;
    for(int i = 0; i < 10; i++)
    {
        if('0' <= hex1[i] && hex1[i] < '0' + 10)
            x = hex1[i] - '0';
        else
            x = hex1[i] - 'A' + 10;
        if('0' <= hex2[i] && hex2[i] < '0' + 10)
            y = hex2[i] - '0';
        else
            y = hex2[i] - 'A' + 10;
        carry = other_carry;
    int z;
        z = (x + y + carry) % 16;
        other_carry = (x + y + carry) / 16; 
        if(0 <= z && z < 10)
            sum[i] = char('0' + z);
        else if(10 <= z && z < 16)
            sum[i] = char('A' + z - 10);
    }
    if(1 == carry && 1 == other_carry)
        cout << "Addition overflow.n";
}

如果我从中删除[0]

cout << "Enter the first hexadecimal number: n";
cin >> hex1[0];
cout << "Enter the second hexadecimal number: n";
cin >> hex2[0];

它允许我进入第二个1D,但输出1D+1D的结果是00000000A2,而不是000000003A。如果我这样做,像F+F这样只有一个字母的十六进制的输出也是错误的。我得到的不是F+F=0000000001E,而是000000000E。

由于您有char作为数据类型,它会读取您所写内容的前两个字母。(在本例中为1和D),并将它们保存在两个不同的数组中。请尝试使用字符串。

问题在于输入的方式,您使用的CHAR数组一次只能取一个值,所以当您键入2位字符时,它实际上将第二位存储在第二个数组中(即hex2[0])。尝试FF,它会给您000000001E(与F+F相同)。为了使其正确,您应该添加一个条件,即如果用户没有键入两位数的字符,则将数组中的第二个元素设置为null(即hex1[1]='\0'),第二个输入也是如此,希望它能帮助u。