微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用字符串实现大数的相加,没有考虑存在负数的情况

题目:用字符串实现大数的相加,没有考虑存在负数的情况

 

 

Code(C):

 

#include<stdio.h>
#include<string.h>

void add(char *s1,char *s2,char *s);

void main()
{
 char s1[100];
 char s2[100];
 char s[100] = {'0'};
 printf("请输入第一个数字\n");
 gets(s1);
 printf("请输入第二个数字\n");
 gets(s2);
 add(s1,s2,s);
 printf("%s+%s = %s\n",s1,s);
}

void add(char *s1,char *s) {  int len1,len2;  int flag = 0,i1,i2,i;  len1 = strlen(s1);  len2 = strlen(s2);  i1 = len1-1;  i2 = len2-1;  i = (len1 > len2 ? len1:len2)+1;  s[i] = '\0';  i--;  while(i1 >= 0 && i2 >= 0)  {   int temp = s1[i1]-'0'+s2[i2]-'0';   if(flag == 1)    temp++;   if(temp >= 10)   {    flag = 1;    temp -= 10;   }   s[i] = temp+'0';   i--;   i1--;   i2--;  }  if(i2 >=0)  {   while(i2 >= 0)   {    int temp = s2[i2]-'0';    if(flag == 1)    {     temp++;    }    if(temp >= 10)    {     flag = 1;     temp -= 10;    }    s[i] = temp+'0';    i--;    i2--;   }  }    else if(i1 >=0)  {   while(i1 >= 0)   {    int temp = s1[i1]-'0';    if(flag == 1)    {     temp++;    }    if(temp >= 10)    {     flag = 1;     temp -= 10;    }    s[i] = temp+'0';    i--;    i1--;   }  }  if(flag == 1)   s[i] = '1'; }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐