高精度小结

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高精度小结相关的知识,希望对你有一定的参考价值。

简单来说就是模拟竖式
乘法和除法是单精度和高精度运算的

#include <bits/stdc++.h>
using namespace std;
char s1[100005], s2[100005];
int len1, len2, b;
vector <int> a;
void remove(vector <int> &a) { while (a.size() > 1 && a.back() == 0) a.pop_back(); }
bool cmp(vector <int> a, vector <int> b) {
	if (a.size() > b.size()) return true;
	else if (a.size() < b.size()) return false;
	for (int i = a.size() - 1; i >= 0; --i) 
		if (a[i] > b[i]) return true;
		else if (a[i] < b[i]) return false;
	return true;
}
vector <int> add(vector <int> a, vector <int> b) {
	if (a.size() < b.size()) return add(b, a);
	vector <int> rs;
	int t = 0;
	for (int i = 0; i < a.size() || t; ++i) {
		if (i < a.size()) t += a[i];	
		if (i < b.size()) t += b[i];
		rs.push_back(t % 10);
		t /= 10;  
	}
	remove(rs);
	return rs;
}
vector <int> sub(vector <int> a, vector <int> b) {
	vector <int> rs;
	int t = 0;
	for (int i = 0; i < a.size(); ++i) {
		t = a[i] - t;
		if (i < b.size()) t -= b[i];
		rs.push_back((t + 10) % 10);
		if (t < 0) t = 1;
		else t = 0;
	}
	remove(rs);
	return rs;
}
vector <int> mul(vector <int> a, int b) {
	vector <int> rs;
	int t = 0;
	for (int i = 0; i < a.size() || t; ++i) {
		if (i < a.size()) t += a[i] * b;
		rs.push_back(t % 10);
		t /= 10;
	}
	remove(rs);
	return rs;
}
vector <int> div(vector <int> a, int b, int &r) {
	vector <int> rs;
	r = 0;
	for (int i = a.size() - 1; i >= 0; --i) {
		r = r * 10 + a[i];
		rs.push_back(r / b);
		r %= b;
	}
	reverse(rs.begin(), rs.end());
	remove(rs);
	return rs;
}

int main() {
        // 这里是除法调用操作,其他都基本一样
	scanf("%s%d", s1 + 1, &b);
	len1 = strlen(s1 + 1);
	for (int i = 1; i <= len1; ++i) a.push_back(s1[i] - \'0\');
	reverse(a.begin(), a.end());
	int r = 0;
	a = div(a, b, r);
	for (int i = a.size() - 1; i >= 0; --i) printf("%d", a[i]);
	printf("\\n%d", r);
	return 0;
}

以上是关于高精度小结的主要内容,如果未能解决你的问题,请参考以下文章

PHP 精度计算引发的灾难性Bug

九度OJ小结

1049 数列的片段和(注意精度!!)

c语言操作符小结

基础小结

c++bug小结