• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C语言之大整数加法

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 void reverse( char *s )        /*将字符串逆置*/
 5 {
 6     int length;
 7     int i = 0;
 8     char temp;
 9     length = strlen( s );
10     while( i < length - i - 1 )
11     {
12         temp = s[i];
13         s[i] = s[length - i - 1];
14         s[length - i - 1] = temp;
15         i++;
16     }
17 }
18 
19 void AddBigNum( char* s1, char* s2, char* result )
20 {
21     int len1 = strlen( s1 );
22     int len2 = strlen( s2 );
23     int acc = 0, temp, i;        /*acc为进位标记*/
24     if( s1 == NULL || s2 == NULL || result == NULL )
25     {
26         return;
27     }
28     reverse( s1 );
29     reverse( s2 );
30     for( i = 0; i < len1 && i < len2; i++ )
31     {
32         temp = s1[i] - \'0\' + s2[i] - \'0\' + acc;        /*计算每位的实际和*/
33         result[i] = temp % 10 + \'0\';        /*通过求余数来确定每位的最终值*/
34         if( temp >= 10 )        /*通过这个if..else..条件来判断是否有进位,并设置进位值*/
35             acc = 1;
36         else
37             acc = 0;
38     }
39     if( i < len1 )        /*两个加数位数不同*/
40     {
41         for( ; i < len1; i++ )
42         {
43             temp = s1[i] - \'0\' + acc;        /*依旧要考虑进位,比如9999 + 1的情况*/
44             result[i] = temp % 10 + \'0\';
45             if( temp >= 10 )        
46                 acc = 1;
47             else
48                 acc = 0;
49         }
50     }
51     if( i < len2 )
52     {
53         for( ; i < len2; i++ )
54         {
55             temp = s2[i] - \'0\' + acc;
56             result[i] = temp % 10 + \'0\';
57             if( temp >= 10 )
58                 acc = 1;
59             else
60                 acc = 0;
61         }
62     }
63 
64     if( acc == 1 )        /*考虑如:123 + 911 = 1034的情况,如果不增加这个条件会得到结果为034,进位被舍弃*/
65 
66         result[i++] = \'1\';
67 
68     result[i] = \'\0\';
69     reverse( result );
70 }
71 
72 main()
73 {
74     char s1[100];
75     char s2[100];
76     char result[100];
77     while((scanf("%s %s",&s1,&s2))!=EOF)
78     {
79     AddBigNum( s1, s2, result );
80     printf( "%s\n", result );
81     }
82 }
View Code

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#基础:在using中创建对象发布时间:2022-07-13
下一篇:
C#ModBus Tcp 报文解析发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap