加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

求两个大数之和

发布时间:2020-12-14 03:28:15 所属栏目:大数据 来源:网络整理
导读:在计算机中,计算大数的时候,一般都不会超过8个字节的数,如果超过了该怎么计算呢,这个时候我们需要将大数转换成数组,然后进行运算。 /*** Name: Add two big number** Author: WJY** Date: 2014-07-26*/#include iostreamusing namespace std;#define AR

在计算机中,计算大数的时候,一般都不会超过8个字节的数,如果超过了该怎么计算呢,这个时候我们需要将大数转换成数组,然后进行运算。

/*
** Name: Add two big number
** Author: WJY
** Date: 2014-07-26
*/
#include <iostream>

using namespace std;

#define ARRAY_SIZE		128

// Get number from stdin
void GetNumber(char buff[],int& size);

// Reverse the elements of the array buffer
void ReverseArray(char buff[],int size);

// Adding two big number
void AddBigNumber(char buff1[],int size1,char buff2[],int size2,char result[],int& size3);

// Show the adding result
void DisplayResult(char result[],int size);


int main(int argc,char *argv[])
{
	char aData[128],bData[128],sum[128];
	int size1 = 0,size2 = 0,resultsize = 0;

	cout << "Add two big number" << endl;
	cout << "Enter the first big number,ending with an enter: " << endl;
	GetNumber(aData,size1);
	cout << "Enter the second big number,ending with an enter: " << endl;
	GetNumber(bData,size2);

	ReverseArray(aData,size1);
	ReverseArray(bData,size2);

	AddBigNumber(aData,size1,bData,size2,sum,resultsize);
	
	DisplayResult(sum,resultsize);
	
	system("pause");
	return 0;
}

void GetNumber(char buff[],int& size)
{
	char next;
	cin.get(next);
	while (next != 'n' && size < ARRAY_SIZE)
	{
		buff[size++] = next;
		cin.get(next);
	}
}

void ReverseArray(char buff[],int size)
{
	char temp;
	int i,j;
	i = 0;
	j = size - 1;

	while (i <= j)
	{
		temp = buff[i];
		buff[i] = buff[j];
		buff[j] = temp;
		i++;
		j--;
	}
}

void AddBigNumber(char buff1[],int& size3)
{
	int i = 0,j = 0;
	int res = 0;
	int carry = 0;

	while (i < size1 && j < size2)
	{
		res = (buff1[i]^0x30) + (buff2[j]^0x30) + carry;
		result[size3++] = (res % 10)^0x30;
		carry = res / 10;
		i++;
		j++;
	}

	// when the first big number greater than the second number
	while (i < size1)
	{
		int ret = (buff1[i]^0x30) + carry;
		result[size3++] = (ret % 10)^0x30;
		carry = ret / 10;
		i++;
	}
	
	//when the second big number greater than the first number
	while (j < size2)
	{
		int ret = (buff2[j]^0x30) + carry;
		result[size3++] = (ret % 10)^0x30;
		carry = ret / 10;
		j++;
	}

	if (i == size1 && j == size2 && carry != 0)
		result[size3++] = carry^0x30;

	result[size3] = '';
}

void DisplayResult(char result[],int size)
{
	ReverseArray(result,size);
	cout << "The adding result is : " << result << endl;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读