高精度在于用字符串的高容量,转化为整形数运算的高精度
用分而治之的思想,逐个处理每一位数,在组合起来,用数组(容器)储存
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool F(string s1, string s2)
{
if (s1.size() > s2.size())
return true;
else if (s1.size() == s2.size())
{
for (int i = s1.size()-1; i >= 0; i--)
{
if (s1[i] < s2[i])
return false;
}
}
else
return false;
return true;
}
void StI(string s1,vector<int>& a1)
{
for (int i = s1.size() - 1; i >= 0; i--)
a1.push_back(s1[i]-'0');
}
void C(vector<int> a1, vector<int> a2, vector<int>& a3)
{
while (a1.size() > a2.size())
a2.push_back(0);
for (int i = 0; i < a1.size(); i++)
{
if (a1[i] < a2[i])
{
a1[i + 1]--;
a1[i] += 10;
a3.push_back(a1[i] - a2[i]);
}
else
a3.push_back(a1[i] - a2[i]);
}
}
int main()
{
string s1, s2;
vector<int> a1, a2, a3;
bool flag;//1表示结果为非负数,0表示为负数;
cout << "请输入被减数和减数:"<<endl;
cin >> s1 >> s2;
flag = F(s1, s2);
if (!flag)
{
swap(s1, s2);
cout << "-";
}
StI(s1, a1);
StI(s2, a2);
C(a1, a2, a3);
int l = a3.size() - 1;
while (a3[l] == 0 && l > 0)l--;
for (int i = l; i >= 0; i--)
cout << a3[i];
return 0;
}