Reputation: 3
I have been asked to make a calculator taking the inputs as a string, so that we can we can calculate with long numbers the result should also be a string. I tried the addition part but it doesn't work with the two numbers being of different lengths. Could someone tell me where my code went wrong and how i can fix it ? Also an idea of how i would divide using this principle.
i = strlen(first);
j = strlen(second);
x = 0;
while(1)
{
z = (first[i-1] - 48) + (second[j-1] - 48) + carry;
carry = z/10;
result1[x] = z%10 + 48;
x++;
i--;
j--;
if(i==0 && j==0)
{ if(carry!=0)
result1[x] = carry + 48;
break;
}
}
i = strlen(result1);
for (i = 0, j = strlen(result1)-1; i < j; i++, j--)
{
c = result1[i];
result1[i] = result1[j];
result1[j] = c;
}
puts(result1);
Upvotes: 0
Views: 136
Reputation: 55392
z = (first[i-1] - 48) + (second[j-1] - 48) + carry;
This won't work if one of i or j is zero or negative. If you want to continue looping until both strings are consumed, then you could use ?: to avoid accessing the array unsafely. You may also find it easier to decrement i and j at the start of the loop.
if(i==0 && j==0)
This won't work if i != j. You need to find a better way to terminate the loop. (With careful conditional logic above you could even continue the loop until the carry is zero too.)
Upvotes: 0
Reputation: 753655
You have to start the summation with the least significant digits in each string; if the sum exceeds 9, you carry 1 over to the next more significant digit sum. Just like you do on paper. This also means you have to organize things so that you know how long each string (number) is, and deal with 'implicit zeroes' in front of the shorter number.
Upvotes: 2