高精度:就是在很大的位数情况下进行运算。(炸int甚至long long)
其基本思想就是用数组或字符串进行模拟加法。模拟进位。 最后遍历数组输出。
附上高精加,减,乘代码。除法以后写了补上。
1. 高精度加法
原题点这里
#include <bits/stdc++.h>
using namespace std;
string a,b,str;
string add(string s1,string s2){
int len1=s1.size();
int len2=s2.size();
if(len1<len2) //保证两个数位数相等,不足首部加0补齐
for(int i=0;i<len2-len1;i++)
s1='0'+s1;
else
for(int i=0;i<len1-len2;i++)
s2='0'+s2;
len1=s1.size();
int j,k=0;
for(int i=len1-1;i>=0;i--){ //模拟加法逐位相加,k表示进位
j=s1[i]-'0'+s2[i]-'0'+k;
s1[i]=j%10+'0';
k=j/10;
}
if(k) s1=char(k+'0')+s1; //判断最高位相加后是否有进位
return s1;
}
int main(){
cin>>a>>b;
str=add(a,b);
cout<<str;
return 0;
}
2. 高精度减法
传送门
#include <bits/stdc++.h>
using namespace std;
string a,b,str;
bool check(string s1,string s2){ //判断两个数的大小,第一个数大就返回true,否则返回false
if(s1.size()>s2.size()) return true;
else if(s1.size()<s2.size()) return false;
else return s1>=s2;
}
string sub(string s1,string s2){
if(check(s2,s1)) s1.swap(s2); //保证大数减去小数
int len1=s1.size();
int len2=s2.size();
int temp=len1-len2;
int j=0;
for(int i=len2-1;i>=0;i--){
if(s1[temp+i]-j<s2[i]){
s1[temp+i]=s1[temp+i]-j-s2[i]+10+'0';
j=1;
}
else{
s1[temp+i]=s1[temp+i]-j-s2[i]+'0';
j=0;
}
}
for(int i=temp-1;i>=0;i--){
if(s1[i]-j>='0'){
s1[i]=s1[i]-j;
j=0;
}
else{
s1[i]=s1[i]-j+10;
j=1;
}
}
s1.erase(0,s1.find_first_not_of('0')); //去掉高位上多余的0
if(s1.empty()) return "0"; //为空则表明两数相等,差为0
else return s1;
}
int main(){
cin>>a>>b;
str=sub(a,b);
if(check(a,b)) cout<<str;
else cout<<"-"<<str; //负数前面加上负号
return 0;
}
3. 高精度乘法
直通车
#include <bits/stdc++.h>
using namespace std;
string a1,b1;
int a[5000],b[5000],c[5000],len1,len2; //数组开多大根据题意而定,a*b结果的位数不大于a+b,此题不大于5000
void mul(){ //乘法模板,记住就好了,用一个数组存放结果
for(int i=0;i<len1;i++)
for(int j=0;j<len2;j++){
c[i+j]+=a[i]*b[j];
c[i+j+1]+=c[i+j]/10;
c[i+j]%=10;
}
}
int main(){
cin>>a1>>b1;
len1=a1.size();
len2=b1.size();
for(int i=0;i<len1;i++) a[len1-1-i]=a1[i]-'0'; //把字符串转换为整形数组
for(int j=0;j<len2;j++) b[len2-1-j]=b1[j]-'0';
mul();
int len3=len1+len2;
while(!c[len3]&&len3>0) len3--; //更新答案位数
for(int i=len3;i>=0;i--)
cout<<c[i];
return 0;
}