3)大数相加问题
http://acm.hdu.edu.cn/showproblem.php?pid=1002
答案代码:
1 #include<iostream> 2 #include<string.h> 3 using namespace std; 4 5 int main(){ 6 char a[1001],b[1001]; 7 int lena ,lenb,len,n,c=1,a1[1001],a2[1001],b1[1001]; 8 cin>>n; 9 while(n--){ 10 cin>>a>>b; 11 lena=strlen(a); 12 lenb=strlen(b); 13 //求他们最大的字符长度 14 len=lena>=lenb?lena:lenb; 15 //将a 和b 的值逆序赋值给a1,b1 16 for (int i = 0; i < lena; i++) 17 { 18 a1[i]=a[lena-1-i]-'0'; 19 } 20 for (int i = 0; i < lenb; i++) 21 { 22 b1[i]=b[lenb-1-i]-'0'; 23 } 24 //不足最长位的数进行最高位补零,为了最高位的进位在len+1位上填0 25 for (int i = lena; i <= len; i++) 26 { 27 a1[i]=0; 28 } 29 for (int i = lenb; i <= len; i++) 30 { 31 b1[i]=0; 32 } 33 //进行对应位数相加 34 for (int i = 0; i <= len; i++) 35 { 36 a2[i]=a1[i]+b1[i]; 37 } 38 //判断是否有进位,有的加后一位加一 39 for (int i = 0; i < len; i++) 40 { 41 if(a2[i]>=10) 42 { 43 a2[i+1]=a2[i+1]+1; 44 a2[i]=a2[i]%10; 45 } 46 } 47 //结果输出: 48 cout<<"Case "<<c<<":"<<endl; 49 c++; 50 51 //注意要是用数组输出时应该进行倒序输出才是正数 52 for (int i = 0; i < lena; i++) 53 { 54 cout<<a[i]; 55 } 56 cout<<" "<<"+"<<" "; 57 for (int i = 0; i < lenb; i++) 58 { 59 cout<<b[i]; 60 } 61 cout<<" "<<"="<<" "; 62 //如果最高位有进位的话输出 63 if(a2[len]>0) 64 cout<<a2[len]; 65 for (int i = len-1; i >=0; i--) 66 { 67 cout<<a2[i]; 68 } 69 cout<<endl; 70 if(n>0) 71 cout<<endl; 72 } 73 return 0; 74 }