I have a C program that can add large numbers and it works fine but I also need to do add smaller numbers but I get a odd output and am not sure where the error is coming from.
#include<stdio.h>
#include<string.h>
int main() {
int num1[255], num2[255], sum[255], m = 0, z, x = 0;
char s1[255], s2[255], in[255];
int l1, l2;
printf("enter the input as a+b=\n");
scanf("%s", in);
for (z = 0; in[z] != '+'; z++) {
s1[z] = in[z];
m++;
}
for (z = m + 1; z < strlen(in) - 1; z++) {
s2[x] = in[z];
x++;
}
for (l1 = 0; s1[l1] != '\0'; l1++)
num1[l1] = s1[l1] - '0';
for (l2 = 0; s2[l2] != '\0'; l2++)
num2[l2] = s2[l2] - '0';
int carry = 0;
int k = 0;
int i = l1 - 1;
int j = l2 - 1;
for (; i >= 0 && j >= 0; i--, j--, k++) {
sum[k] = (num1[i] + num2[j] + carry) % 10;
carry = (num1[i] + num2[j] + carry) / 10;
}
if (l1 > l2) {
while (i >= 0) {
sum[k++] = (num1[i] + carry) % 10;
carry = (num1[i--] + carry) / 10;
}
if (carry != 0) {
sum[k] = carry;
k = k + 1;
}
} else if (l1 < l2) {
while (j >= 0) {
sum[k++] = (num2[j] + carry) % 10;
carry = (num2[j--] + carry) / 10;
}
if (carry != 0) {
sum[k] = carry;
k = k + 1;
}
} else {
if (carry > 0)
sum[k++] = carry;
}
printf("%s+%s=\n", s1, s2);
for (k--; k >= 0; k--)
printf("%d", sum[k]);
return 0;
}
If I enter a values such as:
enter the input as a+b=
9999999999999999999999999999+1=
I get this output which is what I wanted it to be
9999999999999999999999999999+1=
10000000000000000000000000000
When I try something smaller like:
123+456=
The output is different
123ó+456=
16-5-6
I don't know where these numbers are coming from and this keeps occurring with any number less than 9999999999999999999999999999+1= It should work for any number not just a single set.
for (l1 = 0; s1[l1] != '\0'; l1++)
// ^^^^^^^^^^^^^^
Here's a problem: You're checking for '\\0'
in s1
, but you never set any element of s1
to '\\0'
, so this will access uninitialized memory and potentially go out of bounds of the array.
You have the same problem with s2
.
There may be other problems, but this is where I stopped reading.
General comments:
scanf
. %s
with scanf
. It's a buffer overflow waiting to happen. for (z = 0; in[z] != '+'; z++)
loop will go out of bounds if there is no +
in the string). You should probably verify your assumptions and not blindly assume everything is OK.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.