大数加减

#include "iostream"
#include "string"
using namespace std;
struct bign {
	int d[1000];
	int len;
	bign() {//构造函数
		memset(d, 0, sizeof(d));//赋初值为0
		len = 0;
	}
};
bign change(string a);
bign Add(bign a,bign b);
int Judge(bign a, bign b);//判断大小,a>b返回1 a>a>>b;
	bign A=change(a);
	bign B = change(b);
	bign C = Add(A, B);
	cout << "相加的结果" << endl;
	Print(C);
	int judge = Judge(A, B);
	cout<< "相减的结果" << endl;
	if (judge == 1)
	{
		bign D = Sub(A, B);
		Print(D);
	}
	else if (judge == 0)
	{
		bign D = Sub(B, A);
		cout << "-";
		Print(D);
	}
	else
		cout << "相减等于0";
	system("pause");
	return 0;
}
//整数的高位存储在数组的高位
bign change(string a)
{
	bign temp;
	for (int i = 0; i < a.size(); i++)
	{
		temp.d[i] = a[a.size() - 1 - i] - '0';
	}
	temp.len = a.size();
	return temp;
}
bign Add(bign a,bign b)
{
	bign c;
	int jinwei = 0;
	for (int i = 0; i < 1000; i++)
	{
		int temp = a.d[i] + b.d[i]+jinwei;
		c.d[i] = c.d[i]+temp % 10;
		jinwei = temp / 10;//存储着进位
	}
	int num = 0;
	for (int i = 999; i >= 0; i--)
	{
		if (c.d[i] != 0)
			break;
		if (c.d[i] == 0)
			num++;
	}
	c.len = 1000 - num;
	return c;
}
bign Sub(bign a, bign b)
{
	bign c;
	for (int i = 0; i < a.len; i++)
	{
		if (a.d[i] < b.d[i])
		{
			a.d[i] = a.d[i] + 10;
			a.d[i + 1]--;//借位
			c.d[i] = a.d[i] - b.d[i];
		}else
			c.d[i] = a.d[i] - b.d[i];
	}
	int num = 0;
	for (int i = 999; i >= 0; i--)
	{
		if (c.d[i] != 0)
			break;
		if (c.d[i] == 0)
			num++;
	}
	c.len = 1000 - num;
	return c;
}
int Judge(bign a, bign b)
{
	if (a.len > b.len)
		return 1;
	else if (a.len < b.len)
		return 0;
	else if (a.len = b.len)
	{
		for (int i = 0; i < 1000; i++)
		{
			if (a.d[i] > b.d[i])
			{
				return 1;
			}
			else if (a.d[i] < b.d[i])
			{
				return 0;
			}
		}
	}
	return -1;
}
void Print(bign c)
{
	for (int i = c.len - 1; i >= 0; i--)
		cout << c.d[i];
	cout << endl;
}

 

你可能感兴趣的:(大数加减)