逻辑不对 + 变量不初始化 + 内存申请了不释放 + 把 == 写成 =
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *get_s(void);
char *add(char *num1,char *num2);
char *add(char *num1,char *num2)//实现两个字符串相加
{
char*last1=num1;
char*last2=num2;
char*result = NULL;
int count1=0,count2=0;
int mark=0,temp=0,max,digit=0;//mark表示是否需要进位,digit用来表示正在计算的位数
while(*last1++)
{
count1++;
}
last1-=2;
while(*last2++)
{
count2++;
}
last2-=2;
max=count1>count2?count1:count2;
max += 1; // 进位
max += 1; // '\0'
result=(char*)realloc(result,max*sizeof(char));
result[max - 1] = '\0';
digit = max - 1 - 1;
for(;count1!=0&&count2!=0;count1--,count2--)
{
/*
//if(mark=0)
if(mark == 0)
{
temp=*last1+*last2-'0'-'0';
last1--;
last2--;
}
else
{
temp=*last1+*last2-'0'-'0'+1;
last1--;
last2--;
}
*/
temp = (*last1-- - '0') + (*last2-- - '0') + mark;
mark = 0;
if(temp > 9) {
mark = 1;
temp -= 10;
}
result[digit--] = temp + '0';
/*
if(temp>9)
{
result[digit]=temp-10;
mark=1;
digit++;
}
else
{
result[digit]=temp;
mark=0;
digit++;
}
*/
}
char *p = NULL;
char *pe = NULL;
if(count1 != 0) p = last1, pe = num1 - 1;
if(count2 != 0) p = last2, pe = num2 - 1;
while(p != pe) {
temp = (*p-- - '0') + mark;
mark = 0;
if(temp > 9) {
mark = 1;
temp -= 10;
}
result[digit--] = temp + '0';
}
if(mark) result[digit--] = mark + '0';
if(digit == 0) { // 之前多申请了一个进位,全部字符串前移一位
for(size_t i = 0; i < max - 1; ++i) {
result[i] = result[i + 1];
}
result = realloc(result, max - 1);
}
return result;
}
char *get_s(void)//获取字符串
{
char ch;
//char*num;
char*num = NULL;
int count=0;
if((ch=getchar())!='\n')
{
num=(char*)realloc(num, 2);
num[count++]=ch;
num[count++]='\0';
} else {
num=(char*)realloc(num, 1);
num[count++]='\0';
return num;
}
char *next = get_s();
size_t size = strlen(next);
if(size) {
num = realloc(num, size + count);
strcat(num, next);
}
free(next);
return num;
}
int main(void)
{
char*num1;
char*num2;
char*result;
printf("请输入一个整数:");
num1=get_s();
printf("请输入一个整数:");
num2=get_s();
result=add(num1,num2);
printf("计算结果是:%s\n", result);
free(result);
free(num2);
free(num1);
return 0;
}
|