C++十六进制计算器运行时错误
C++ Hexadecimal calculator run time error
我正在努力让这件事正常工作,但我就是做不到。例如,它添加了像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。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 试图找出为什么我会收到运行时错误?
- 迭代二维矢量时发生运行时错误
- C++十六进制计算器运行时错误