思路:字符串模拟加法,设置carry进位,右对齐字符串,从右向左相加,从左到右输出结果。
#include <iostream> using namespace std; int main() { const int N =1005; string a,b,aa,bb; int n; cin>>n; for(int i=0;i<n;i++) { cin>>a>>b; aa = a; bb = b; if(a.length()<b.length()) a.insert(0,b.length()-a.length(),'0'); else b.insert(0,a.length()-b.length(),'0'); b.insert(0,1,'0'); a.insert(0,'0'); int carry = 0; char c[N]={0}; for(int j=a.length()-1; j>=0; j--) { c[j] = carry + a[j] + b[j] - '0' - '0'; carry = c[j]/10; c[j] %= 10; } int m=0; while(c[m]=='\0') m++; cout<<"Case "<<i+1<<":\n"<<aa<<" + "<<bb<<" = "; for(;m<a.length();m++) cout<<char(c[m]+'0'); cout<<endl; if(i!=n-1) cout<<endl; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。