# 两个大数相加有关问题

www.MyException.Cn  网友分享于：2013-04-26  浏览：17次

#include <iostream>

using namespace std;
#define ARRAY_SIZE 50

//Enter a big number, and store it as a string into an array ch,
//the size is the numbers of char.
void inputNumbers(char ch[], int& size);

//Reverse the elements of the array ch.
void reverseArray(char ch[], int size);

//Adding two big numbers, and the result will be stored in the array ch3,
//and return the size of the array ch3.
void computeAdding(char ch1[], int size1, char ch2[], int size2, char ch3[], int& size3);

//show the adding result.
void displayResult(char ch[], int size);

int main()
{
char ch1[ARRAY_SIZE], ch2[ARRAY_SIZE], result[ARRAY_SIZE];
int size1 = 0, size2 = 0, resultSize = 0;

cout << "Enter the first big number, ending with an enter:" << endl;
inputNumbers(ch1, size1);
cout << "Enter the second big number, ending with an enter:" << endl;
inputNumbers(ch2, size2);

reverseArray(ch1, size1);
reverseArray(ch2, size2);

computeAdding(ch1, size1, ch2, size2, result, resultSize);
displayResult(result, resultSize);

system("pause");
return 0;
}

//Function inputNumbers
void inputNumbers(char ch[], int& size)
{
char next;

cin.get(next);
while (next != '\n' && size < ARRAY_SIZE)
{
ch[size++] = next;
cin.get(next);
}
}//inputNumbers

//Function reverseArray
void reverseArray(char ch[], int size)
{
int i = 0, j = size-1;
char temp;

while (i <= j)
{
temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
i ++;
j --;
}
}//end reverseArray function

//function computeAdding
void computeAdding(char ch1[], int size1, char ch2[], int size2, char ch3[], int& size3)
{
int i = 0, j = 0;
char result;

while (i < size1 && j < size2)
{
result = ch1[i] + ch2[j] - 48;
if (result >= '10')
{
if (size1 == i && j < size2) //If size1 < size2
ch2[j] = ch2[j] + 1;
else
ch1[i] = ch1[i] + 1;
ch3[size3++] = result - '10' + '0';
}
else
ch3[size3++] = result;
i ++;
j++;
}
if (size1 < size2)//If the ch1 has more bits, execute this clause
{
for (i = size1; i < size2; i++)
{
ch3[size3++] = ch2[i] ;
}
}
else if (size1 > size2)
{
for (i = size2; i < size1; i++)
{
ch3[size3++] = ch2[i] ;
}

}
}//End reverseArray

//function displayResult
void displayResult(char ch[], int size)
{
reverseArray(ch, size);//make the number to be normal

cout << "The adding result is:" ;
for (int i = 0; i < size; i++)
cout << ch[i] ;
cout << endl;
}

------解决方案--------------------

C/C++ code
```
void computeAdding(char ch1[], int size1, char ch2[], int size2, char ch3[], int& size3)
{
int i,cf,tmp;

for( i=0,cf=0; i<size1&&i<size2; i++)
{
tmp = (ch1[i]-'0') + (ch2[i]-'0') + cf;
ch3[i]= tmp%10+'0';
cf = tmp/10;
}
while( i<size1 ) {
tmp = (ch1[i]-'0')+cf;
ch3[i] = tmp%10+'0';
cf = tmp/10;
i++;
}
while( i<size2 ){
tmp = (ch2[i]-'0') +cf;
ch3[i] = tmp%10 +'0';
cf = tmp/10;
i++;
}
if( cf ) { ch3[i]= cf+'0'; i++;}
ch3[i]='\0';

size3 = i;

}//End reverseArray
```