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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include <iostream>
using namespace std;
const int maxSize = 20;
void readIn (int num1[], int& sizeNum1);
void printOut(int num1[], int sizeNum1);
void add(int num1[], int sizeNum1, int num2[], int sizeNum2, int sum[], int & sumSize);
int main()
{
int num1[maxSize], num2[maxSize], sum[maxSize];
int sizeNum1, sizeNum2, sumSize;
for(int i = 0; i < maxSize; i++)
{
num1[i] = 0;
num2[i] = 0;
sum[i] = 0;
}
readIn(num1, sizeNum1);
readIn(num2, sizeNum2);
add(num1, sizeNum1, num2, sizeNum2, sum, sumSize);
cout << "The sum of ";
printOut(num1, sizeNum1);
cout << " and ";
printOut(num2, sizeNum2);
cout << " is ";
printOut(sum, sumSize);
cout << endl;
return 0;
}
void readIn(int num1[], int& sizeNum1)
{
char digit[maxSize];
char convert;
int index = 0;
cout << "Please enter an integer up to 20 digits: ";
cin.get(convert);
if (convert == '\n')
{
cin.get(convert);
}
while (isdigit(convert) && index < maxSize)
{
digit[index] = convert;
index++;
cin.get(convert);
}
sizeNum1 = index;
int jIndex = 0;
while (index > 0)
{
index--;
num1[jIndex] = digit[index] - '0';
jIndex++;
}
}
void printOut(int num1[], int sizeNum1)
{
for (int i = 0; i < sizeNum1; i++)
cout << num1[sizeNum1 - i - 1];
}
void add(int num1[], int sizeNum1, int num2[], int sizeNum2, int sum[], int & sumSize)
{
int index;
for(index = 0; index < maxSize - 1; index++)
{
sum[index] = (num1[index] + num2[index]) % 10;
sum[index + 1] = (num1[index] + num2[index]) / 10;
index++;
}
sumSize = index;
if ((num1[index] + num2[index]) /20 > 0)
{
cout << "Sum is too large. " << endl;
}
}
|