码迷,mamicode.com
首页 > 其他好文 > 详细

Long integer Adder-大整数相加

时间:2014-09-12 15:23:04      阅读:185      评论:0      收藏:0      [点我收藏+]

标签: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-大整数相加

标签:long integer adder-大整数相加

原文地址:http://9320314.blog.51cto.com/9310314/1551510

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!