实现字符串输入整数取相加的结果
代码好像是正确的 实验了几组相加的结果
但是如果999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999999999999999 的结果会有一个冒号 是什么原因导致的呢?
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
char *FZ(char *a);
char *FZ(char *a)
{
char ch;
int n,m,i;
int s = strlen(a);
m = s/2;
i = s;
for(n = 0;n < m; n++) //高位换低位只换到一半的值 所以n<m 而不是n<i
{
ch = a[n];
a[n] = a[--i];
a[i] = ch;
}
a[s] = '\0';
// printf("打印ptr反转:%s结束\n\n",a);
return a;
}
char *SR();
char *SR()
{
int i,count = 0;
char num;
char *ptr = NULL;
printf("请输入一个整数:");
do
{
scanf("%c",&num);
count++;
ptr = (char *)realloc(ptr,count * sizeof(char));
if(ptr == NULL)
{
exit(1);
}
ptr[count - 1] = num;
}while(num != '\n');
ptr[count - 1] = '\0';
// printf("打印ptr:%s结束\n\n",ptr);
return ptr;
}
int main()
{
char *a = SR();
char *b = SR();
int MIN,MAX,F;
if(strlen(a) > strlen(b))
{
MIN = strlen(b);
MAX = strlen(a);
F = 0;
}
else
{
MIN = strlen(a);
MAX = strlen(b);
F = 1;
}
a = FZ(a);
// printf("打印ptr a 反转:%s结束\n\n",a);
b = FZ(b);
// printf("打印ptr b 反转:%s结束\n\n",b);
int s = 0;
char *c = (char *)malloc((MAX+1) * sizeof(char));
if(c == NULL)
{
exit(1);
}
int n;
for(n = 0;n < MIN; n++)
{
if(a[n]+b[n]+s < 106)
{
c[n] = (a[n]+b[n]+s) % 48 + 48;
s = 0;
}
else
{
c[n] = (a[n]+b[n]+s) % 48 + 38;
s = 1;
if(n == MIN-1 && MIN == MAX)
{
c = (char *)realloc(c,sizeof(char));
if(c == NULL)
{
exit(1);
}
c[n+1] = '1';
c[n+2] = '\0';
}
}
}
if(MIN != MAX)
{
if(F == 0)
{
c[n] = a[n]+s;
while(n < MAX - 1)
{
n++;
c[n] = a[n];
}
}
if(F == 1)
{
c[n] = b[n]+s;
while(n < MAX - 1)
{
n++;
c[n] = b[n];
}
}
c[MAX] = '\0';
}
c = FZ(c);
printf("计算结果是:");
printf("%s",c);
free(a);
free(b);
free(c);
return 0;
}
代码好像是正确的 实验了几组相加的结果
但是如果999999999999999999999999999999999999999 + 9999999999999999999999999999999999999999999999999999 的结果会有一个冒号 是什么原因导致的呢?