You need to think about how the bigint is stored in memory. You have a vague idea, but you
must be specific.
For your purposes (and what you seem to be trying to do):
Each individual digit of the number is stored in an int array, where each element of the array is a digit in 0 through 9.
The
order in which you store the digits matters. You should store the least-significant digit (the rightmost) in index 0.
So, the number "12345" would be stored as:
int num[20] = { 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Notice that unused digits are zeros. This is fine, since that is the same as "00000000000000012345".
You will need to fix your calculations on lines 63 and 64.
Also, it is a good idea not to hardcode ASCII values. It is easier to understand what you are doing just to say
ascii_value - '0'
anyway.
Since we have stored the number with the most significant digits at later positions in the array, you don't actually have to remember what the actual number of digits are, right?
In other words, adding
is the same as adding
right?
Once you fix that, your main function should have code something like this:
1 2 3 4
|
int n1[20] = {0};
cout<<"Please enter the first positive integer (20 digits at the most): ";
readnum(n1);
|
The way the number is defined also makes your addition function
much simpler -- you only need lines 78 through 83:
78 79 80 81 82 83 84 85 86 87 88 89 90
|
void addnum(int a[20], int b[20], int sum[20])
{
int carry=0;
int temp;
int i;
for(i=0; i<20; i++)
{
temp=a[i]+b[i]+carry;
sum[i]=temp%10;
carry=temp/10;
}
}
|
(All I did was chop out stuff you didn't need. Oh, and change the return type to
void. Since your bignums are fixed at twenty-digits long, there is no point in caring about overflow (if carry != 0 at the end of the function).
I'll leave figuring out how to display the number up to you. You've got the right idea already, just remember that we normally write "00012" as just "12".
Hope this helps.