所有的高精度计算都很相似(除以外),都是模拟小学生算数列竖式,借位进位之类的,最主要的难点应该就只有判重和0上了吧,好像没什么可说的了233
现在写下模板,都是最水的纯蒟蒻打法的代码,直接A掉以后粘过来的,所以很丑
很丑但很直白╮(~▽~)╭
高精度加法模板:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#define maxn 505
using namespace std;
string sta,stb;
int a[maxn];
int b[maxn];
int c[maxn];
int main(){
while(cin>>sta>>stb){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
a[0] = sta.size();
b[0] = stb.size();
for(int i=1;i <= a[0];i++){
a[i] = sta[a[0]-i]-'0';
}
for(int i=1;i <= b[0];i++){
b[i] = stb[b[0]-i]-'0';
}
c[0] = max(a[0],b[0]);
for(int i=1;i <= c[0];i++){
int x = a[i]+b[i]+c[i];
c[i] = x%10;
c[i+1] = x/10;
}
if(c[c[0]+1])
c[0]++;
while(c[c[0]]==0&&c[0]>1){
c[0]--;
}
for(int i = c[0];i >= 1;i--)
cout<<c[i];
}
cout<<endl;
return 0;
}
高精度减法模板:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string sta,stb,sth;
int a[5550];
int b[5550];
int c[5550];
bool pd;
int main(){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
cin>>sta>>stb;
int sa = sta.size();
int sb = stb.size();
if(sa < sb){
sth = sta;
sta = stb;
stb = sth;
swap(sa,sb);
pd = 1;
}
if(sa == sb){
for(int i = 0;i <=sa-1;i++){
if(sta[i] == stb[i]){
continue;
}
if(sta[i] > stb[i]){
break;
}
if(sta[i] < stb[i]){
sth = sta;
sta = stb;
stb = sth;
pd = 1;
break;
}
}
}
// for(int i = 0;i <= sa-1;i++){
// cout<<sta[i];
// }
//cout<<endl;
// for(int i = 0;i <= sb-1;i++){
// cout<<stb[i];
// }
// cout<<endl;
for(int i=1;i <= sa;i++){
a[i] = sta[sa-i]-'0';
}
for(int i=1;i <= sb;i++){
b[i] = stb[sb-i]-'0';
}
int osu;
for(int i = 1;i <= sa;i++){
if(a[i] >= b[i]){
c[i] = a[i] - b[i];
}
else{
a[i+1] -= 1;
a[i] += 10;
c[i] = a[i] - b[i];
}
}
if(c[sa] == 0){
sa--;
}
if(pd == 1)
printf("-");
for(int i = sa;i >= 1;i--){
printf("%d",c[i]);
}
printf("\n");
return 0;
}
高精度乘法:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#define maxn 505
using namespace std;
string sta,stb;
int a[maxn];
int b[maxn];
int c[maxn];
int main(){
while(cin>>sta>>stb){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
a[0] = sta.size();
b[0] = stb.size();
for(int i=1;i <= a[0];i++){
a[i] = sta[a[0]-i]-'0';
}
for(int i = 1;i <= b[0];i++){
b[i] = stb[b[0]-i]-'0';
}
for(int i=1;i<=a[0];i++)
for(int j =1;j<=b[0];j++)
c[i+j-1] += a[i]*b[j];
c[0] = a[0]+b[0];
for(int i=1;i<=c[0];i++){
c[i+1] += c[i]/10;
c[i] %= 10;
}
while(c[c[0]]==0&&c[0]>1)
c[0]--;
for(int i=c[0];i>=1;i--)
cout<<c[i];
}
cout<<endl;
return 0;
}
THE END
By Peacefuldoge