C++实现的一个简单两个大数相加程序!

#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's definition
void computeAdding(char ch1[], int size1, char ch2[], int size2, char ch3[], int& size3)
{
    int i,
          tmp,                  //As the temporary sum of two array elements.
          carryBit = 0;    //The carry-bit is initialized to zero


    for (i = 0; i < size1 && i < size2;  i++)
    {
        tmp = (ch1[i]-'0') + (ch2[i]-'0') + carryBit;
        ch3[i] = tmp % 10 + '0';
        carryBit = tmp/10;
    }
    while ( i<size1 ) { //If the array ch1 has more bits, execute this while loop.
        tmp = (ch1[i] - '0') + carryBit;
        ch3[i] = tmp % 10 + '0';
        carryBit = tmp / 10;
        i ++;
    }
    while ( i < size2 ){
        tmp = (ch2[i] - '0') + carryBit;
        ch3[i] = tmp % 10 +'0';
        carryBit = tmp / 10;
        i ++;
    }
    if( carryBit)
{
      ch3[i] = carryBit + '0';
      i ++;
     }
    ch3[i] = '\0';


    size3 = 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;
}

















上一篇:PyQt5 技术篇-设置QTableWidget表格组件默认值实例演示,如何获取QTableWidget表格组件里的值,获取表格的行数和列数


下一篇:开发常用镜像站 - 阿里云镜像站