计算两个数相加时进位的个数

 1 /**
 2     计算两个数相加时进位的个数
 3 */
 4 #include <iostream>
 5 #include <stdio.h>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     freopen("in.txt","r",stdin);
11     int a,b;
12     while(scanf("%d%d",&a,&b) && (a != 0 || b!= 0))
13     {
14         int c = 0,ans = 0;
15         for(int i = 9;i >= 0;i ++)
16         {
17            c = (a % 10 + b % 10 + c) >9 ? 1 : 0;
18             ans += c;
19             a /= 10;
20             b /=  10;
21         }
22         printf("%d
",ans);
23     }
24     return 0;
25 }

因为给的数的最多为9位 所以i的循环到9 表示将每一位参与到运算

c = (a % 10 + b % 10 + c) >9 ? 1 : 0;  c值用来判断这两位数相加是否产生进位
ans += c;  ans用来表示总共的进位个数
a /= 10;b /= 10; 更新到a b 的下一位