xd程序设计1:基于vector的高精度算法

#include <bits/stdc++.h>
using namespace std;

vector<int> init(string &a) {
	vector<int> A;
	for (int i = a.size() - 1; i >= 0; i--)
		A.push_back(a[i] - '0');
	return A;
}//将字符串初始化为数组

bool cmp(vector<int> &a, vector<int> &b) {//传引用更快
	if (a.size() != b.size())
		return a.size() > b.size();//首先位数更大的数是“大数”
	for (int i = a.size() - 1; i >= 0; i--) {
		if (a[i] != b[i])
			return a[i] > b[i];//位数相同时,每一位上数更大的是“大数:
	}
	return true;//位数相同并且每一位上的数都相同,它们相减就为零
}//做减法时,我们要保证是“大数”减“小数”

vector<int> add(vector<int> &a, vector<int> &b) {
	vector<int> c;
	int t = 0;
	for (int i = 0; i < a.size() || i < b.size(); i++) {
		if (i < a.size())
			t += a[i];
		if (i < b.size())
			t += b[i];
		c.push_back(t % 10);
		t /= 10;
	}
	if (t)
		c.push_back(1);//进了一位一,此时要再加上一位一
	return c;
}

vector<int> sub(vector<int> &a, vector<int> &b) {
	int t = 0;
	vector<int> c;
	for (int i = 0; i < a.size(); i++) {
		t = a[i] - t;
		if (i < b.size())
			t -= b[i];
		c.push_back((t + 10) % 10);
		if (t < 0)
			t = 1; // 如果t < 0,说明不够减,需要借位,把t赋值为1,就是在下一次执行中,A的当前位会减掉t
		else
			t = 0; // 否则够减,赋值为0,不用借位
	}
	while (c.size() > 1 && c.back() == 0)
		c.pop_back();//需要删除前导零直到只剩下一个零为止
	return c;
}

void output(vector<int> &a) {//输出函数
	for (int i = a.size() - 1; i >= 0; i--)
		cout << a[i];
	cout << endl;
}

int main() {
	string a, b;
	char c;
	while (cin >> a >> c >> b) {//将输入写进while的条件中 可以进行多次计算
		auto A = init(a);
		auto B = init(b);
		if (c == '+') {
			auto C = add(A, B);//if语句对应不同的情况
			output(C);
		}

		if (c == '-') {
			if (cmp(A, B)) {
				auto C = sub(A, B);
				output(C);
			} else {
				auto C = sub(B, A);
				cout << '-';
				output(C);
			}
		}
	}
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值