当前位置: 代码迷 >> 综合 >> 高精度(加减乘除)
  详细解决方案

高精度(加减乘除)

热度:74   发布时间:2023-12-01 01:30:20.0
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>using namespace std;//引用速度快
vector<int> add(vector<int>& a, vector<int>& b) {if (a.size() < b.size())return add(b, a);vector<int> c;int t = 0;for (int i = 0; i < a.size(); i++){t += a[i];if (i < b.size())t += b[i];c.push_back(t % 10);t /= 10;}if (t)c.push_back(t);return c;
}int main()
{int n, m, e;vector<int>v1, v2;string s1, s2;cin >> s1 >> s2;//倒着存方便模拟加法for (int i = s1.length() - 1; i >= 0; i--)v1.push_back(s1[i] - '0');for (int i = s2.length() - 1; i >= 0; i--)v2.push_back(s2[i] - '0');auto c = add(v1, v2);//auto c相当于vector<int> cfor (int i = c.size() - 1; i >= 0; i--)cout << c[i];cout << endl;return 0;
}

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>using namespace std;//c = a - b 判断a,b谁大
bool cmp(vector<int>& a, vector<int>& b) {if (a.size() != b.size())return a.size() > b.size();else{for (int i = a.size() - 1; i >= 0; i--) {if (a[i] != b[i])return a[i] > b[i];}}return true;
}//c = a - b
vector<int> sub(vector<int>& a, vector<int>& b) {vector<int> c;int t = 0;//进位for (int i = 0; i < a.size(); i++){t = a[i] - t;if (i < b.size())t = t - b[i];c.push_back((t + 10) % 10);if (t < 0)t = 1;else t = 0;}if (c.size() > 1 && c.back() == 0)c.pop_back();//去除前导 0return c;
}int main()
{int n, m, e;vector<int>v1, v2;string s1, s2;cin >> s1 >> s2;//倒着存 方便模拟减法for (int i = s1.length() - 1; i >= 0; i--)v1.push_back(s1[i] - '0');for (int i = s2.length() - 1; i >= 0; i--)v2.push_back(s2[i] - '0');if (cmp(v1, v2)) {auto c = sub(v1, v2);for (int i = c.size() - 1; i >= 0; i--)cout << c[i];cout << endl;}else//结果为 - 先输出‘-’{auto c = sub(v2, v1);cout << "-";for (int i = c.size() - 1; i >= 0; i--)cout << c[i];cout << endl;}return 0;
}

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>using namespace std;vector<int> mul(vector<int>& a, int b) {vector<int> c;int t = 0;//进位//模拟乘法 当进位不为零时也要继续for (int i = 0; i < a.size() || t ; i++) {if (i < a.size())t += a[i] * b;c.push_back(t % 10);t /= 10;}return c;
}int main()
{int n, m, e;vector<int>v1;string s1;cin >> s1 >> n ;for (int i = s1.length() - 1; i >= 0; i--)v1.push_back(s1[i] - '0');auto c = mul(v1, n);for (int i = c.size() - 1; i >= 0; i--)cout << c[i];cout << endl;return 0;
}

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>using namespace std;
//商c 余 r
vector<int> div(vector<int>& a, int b, int &r) {vector<int> c;r = 0;for (int i = a.size() - 1; i >= 0 ; i--) {//除法从高位开始 r = r * 10 + a[i];c.push_back(r / b);r %= b;}reverse(c.begin(), c.end());//reverse 反转区间while (c.size() > 1 && c.back() == 0)c.pop_back();return c;
}int main()
{int n, m, e;vector<int>v1;string s1;cin >> s1 >> n ;for (int i = s1.length() - 1; i >= 0; i--)v1.push_back(s1[i] - '0');auto c = div(v1, n, e);for (int i = c.size() - 1; i >= 0; i--)cout << c[i];cout << endl << e <<  endl;return 0;
}