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
|
#include <iostream>
#include <string>
using namespace std;
// Do not change these function prototypes:
void readBig(int[]);
void printBig(int[]);
void addBig(int[], int[], int[]);
// This constant should be 100 when the program is finished.
const int MAX_DIGITS = 100;
//There should be no changes made to the main program when you turn it in.
int main()
{
// Declare the three numbers, the first, second and the sum:
int number1[MAX_DIGITS]={}, number2[MAX_DIGITS]={}, sum[MAX_DIGITS]={};
bool finished = false;
char response;
while (! finished)
{
cout << "Please enter a number up to " << MAX_DIGITS << " digits: ";
readBig(number1);
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(number2);
addBig(number1, number2, sum);
printBig(number1);
cout << "\n+\n";
printBig(number2);
cout << "\n=\n";
printBig(sum);
cout << "\n";
cout << "test again?";
cin>>response;
cin.ignore(900,'\n');
finished = toupper(response)!= 'Y';
}
return 0;
}
//ReadBig will read a number as a string,
//It then converts each element of the string to an integer and stores it in an integer array.
//Finally, it reverses the elements of the array so that the ones digit is in element zero,
//the tens digit is in element 1, the hundreds digit is in element 2, etc.
//AddBig adds the corresponding digits of the first two arrays and stores the answer in the third.
//In a second loop, it performs the carry operation.
//PrintBig uses a while loop to skip leading zeros and then uses a for loop to print the number.
//FUNCTIONS GO BELOW
void readBig(int number[MAX_DIGITS])// This function below will read an input number as a string then input that
// into an array.
{
string read="";
cin>>read;
//number[0] = read.length();
for (int i=0; i < MAX_DIGITS && i < read.length(); i++){
number[i] = int (read[i]-'0');
}
}
// This function below will display the number.
void printBig(int number[MAX_DIGITS])
{
int digit=0; //first val counter
for (int i=MAX_DIGITS+1; i>=1; i--) {//i=highest val, while i isnt equal to 1, decrease by one til.
if(number[i]==0 && digit>=1)cout <<""; // clears leading zeros and checks for placeholder zeros
else cout << number[i]; digit++; // else print val and check for beginning of number.
}
}
void addBig(int number1[MAX_DIGITS], int number2[MAX_DIGITS], int sum[MAX_DIGITS])
//The code below sums the arrays.
{
int c=0;
for(int i=1;i<=MAX_DIGITS;i++){
c=number1[i] + number2[i];
sum[i]=c;
if(c<number1[i] && c<number2[i]) sum[i+1]=number1[i] +number2[i]+1;
}
}
|