1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#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";
}
|