首页 > 代码库 > Long integer Adder-大整数相加
Long integer Adder-大整数相加
Long integer Adder-大整数相加
以字符读取,然后翻转,相加输出。
//Long integer Adder #include<iostream> #include<cstdlib> using namespace std; void input(int a[],int b[],int& size1,int& size2); void process(int a[],int b[],int c[]); void output(int c[]); int main() { int a[20] = {0},b[20] = {0},c[20] = {0}; int size1 = 0,size2 = 0; //a[20]=b[20]=c[20]={0}; input(a,b,size1,size2); //cout<<a[0]<<" "<<a[2]<<" "<<b[0]<<" "<<b[2]<<endl; process(a,b,c); //cout<<c[0]<<endl; cout<<"The sum of the two numbers is : "; output(c); return 0; } void input(int a[],int b[],int& size1,int& size2) { cout<<"Please inout two numbers:\n"; char ch; int i = 0; int tem; cin.get(ch); while(ch >= ‘1‘ && ch <= ‘9‘) { a[i] = static_cast<int>(ch)-48; size1 ++; i++; cin.get(ch); } //cout<<size1<<endl; cin.get(ch); i = 0; while(ch >= ‘1‘ && ch <= ‘9‘) { b[i] = static_cast<int>(ch)-48; size2 ++; i++; cin.get(ch); } //cout<<size2<<endl; for(int i = 0;i < size1/2;i++) { tem = a[i]; a[i] = a[size1 - i - 1]; a[size1 - i - 1] = tem; } for(int i = 0;i < size2/2;i++) { tem = b[i]; b[i] = b[size2 - i -1]; b[size2 - i -1] = tem; } } void process(int a[],int b[],int c[]) { int i = 0; while(i < 19) { //cout<<a[i]<<" "<<b[i]<<endl; if((a[i] + b[i]) >= 10) { c[i] += a[i] + b[i] - 10; c[i+1] =c[i+1] + 1; //cout<<c[i+1]<<endl; } else c[i] += a[i] + b[i]; //cout<<c[i]<<endl; i++; } //cout<<c[3]<<endl; } void output(int c[]) { int i; for(i = 19;c[i] == 0; i--) ; //cout<<i<<endl; for(int j = i;j >= 0;j--) cout<<c[j]; cout<<endl; }
结果:
Please inout two numbers: 1234 5678 The sum of the two numbers is : 6912
Please inout two numbers: 123 456666 The sum of the two numbers is : 456789
Long integer Adder-大整数相加
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。