解析: 这道题是要求进位的个数,然后对进位数逐一输出合适的表达式。如果投机取巧,以为通过简单的逐位运算的方法,
如果没有严密的讨论与测试,是永远会WA的。
提供几个一般的数据: 555 555 3 //最简单的情况,进位加一
1 99 2 //要考虑相对大小和再进位
1 999 3 //依然
我写了一个较为通用的算法,不仅可以算出进位数,而且可以得出具体值,可以无限扩大数的大小。
1 #include <iostream> 2 #include <string.h> 3 using namespace std; 4 int main() 5 { 6 char s1[10],s2[10],temp[10]; 7 int i,m1,m2,luffy,count; 8 while(cin>>s1>>s2){ 9 if(strcmp(s1,s2)==0&&strcmp(s1,"0")==0) 10 break; 11 m1=strlen(s1); 12 m2=strlen(s2); 13 count = 0; 14 if(m1<m2){ //如果s2长,则交换字符串 15 strcpy(temp,s1); 16 strcpy(s1,s2); 17 strcpy(s2,temp); 18 } 19 m1=strlen(s1); 20 m2=strlen(s2); 21 //确保s1是最长的字符串 22 luffy=m1-m2; 23 //先加上s2各个位的字符数,直到s2结束 24 for(i=m1-1;i-luffy>=0;i--) 25 s1[i]+=s2[i-luffy]-48; 26 for(i=m1-1;i>0;i--) 27 if(s1[i]>'9'){ 28 s1[i]-=10; //顺便算下 29 s1[i-1]++; 30 count++; 31 } 32 if(s1[0]>'9'){ 33 s1[0]-=10; 34 count++; 35 } 36 if(count== 0) 37 cout<<"No carry operation."<<endl; 38 else if(count == 1) 39 cout<<"1 carry operation."<<endl; 40 else 41 cout<<count<<" carry operations."<<endl; 42 } 43 return 0; 44 }