这是C语言试题上的,请不要给我C++的直接调用的函数,就用C语言的基础知识自己写函数。
编写函数void AddBigInt(char *result,char *str1,*str2),该函数求用str1和str2表示的两个整数的和,将结果放在result中。
大家就不要直接复制网上的四则运算那个了,我看了一晚上没弄懂,最好用比较简单的方式实现(不要涉及太高深的C语言知识,笨一点没关系,这个是学完数组和指针后的题目,估计与数组和指针这部分有关系)
兄弟,麻烦你把主函数一起发过来吧,我这里运行有点问题,好像是头文件出错,我用的vc6.0绿色版。
追答#include
void AddBigInt(char *result,char *str1,char *str2)
{
int i,a,b,c;
int x = 0; //进位值,初始为0
char c1,c2;
for(i = 0;;i++) //计算str1/str2的长度
{
if(*(str1 + i) == '\0')
{
a = i - 1;
break;
}
}
for(i = 0;;i++)
{
if(*(str2+i) == '\0')
{
b = i - 1;
break;
}
}
if(a > b) //result的最大可能长度为str1/str2中长度最大者+1
c = a + 1;
else
c = b + 1;
*(result + c + 1) = '\0'; //添加字符串结束标志
for(i = 0;c >= i;i++) //由后往前计算result对各位的值,直到得出*result的值
{
if(a < i)
c1 = '0'; //该字符串中不存在该位则取'0'值,下同
else
c1 = *(str1 + a - i); //将str1的各位依次赋给c1,下同
if(b < i)
c2 = '0';
else
c2 = *(str2 + b - i);
//计算对应位
*(result + c - i) = ( c1 - '0' + c2 - '0' + x) % 10 + '0';
x = ( c1 - '0' + c2 - '0' + x) / 10 ;
}
if(*result == '0') //如果result的第一位为'0',则去掉该位
{
for(i = 0;*(result + i);i++)
*(result + i) = *(result + i+1);
}
}
int main(void)
{
char str1[200],str2[200],result[200];
printf("Input str1:");
gets(str1);
printf("Input str2:");
gets(str2);
AddBigInt(result, str1,str2);
printf("result:%s\n",result);
return 0;
}