高精度加法与减法总结
高精度计算:由于有些整数过大,需要计算会超过数值范围
int
4字节8位可表达位数:2^32=42 9496 7296
范围:-21 4748 3648 ~ 21 4748 3647 (21*10^8)
long long
8字节8位可表达位数:2^64=1844 6744 0737 0960 0000
范围:-922 3372 0368 5477 5808 ~ 922 3372 0368 5477 5807 (922*10^16)
因此用数组办法代替整型数来计算。
列如1234567891011;
储存为a[0]=13//位数
a[1]–a[13] 为1101987654321//倒着储存,个位在前
高精度加法
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
void input(string s, int c[]);//将输入文本转化为数组
void add();//高精度相加
void print(int c[]);//数组输出
const int N=1000+5;
int a[N],b[N];//倒着存
int main(){
string s1,s2;
while(cin >> s1 >> s2){
input(s1,a);
input(s2,b);
add();//数组a,b是全局变量
print(a);
cout << endl;
}
return 0;
}
void input(string s, int c[]){
c[0]=s.size();
for(int i=1;i<=c[0];i++){
c[i]=s[c[0]-i]-'0';//注意减'0'
}
}
void add(){
if(b[0]>a[0]) a[0]=b[0];
int jin=0;//这种方法方便
for(int i=1;i<=a[0];i++){
a[i]=a[i]+b[i]+jin;
jin=a[i]/10;
a[i]%=10;
}
if(jin) {
a[0]++;
a[a[0]]=jin;
}
}
void print(int c[]){
if(c[0]==0) {//特判
cout << '0';
return;
}
for(int i=c[0];i>=1;i--){
cout << c[i];
}
}
高精度减法
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
void input(string s, int c[]);
void cut();
void print(int c[]);
const int N=1000+5;
int a[N],b[N];
int main(){
string s1,s2;
while(cin >> s1 >> s2){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
input(s1,a);
input(s2,b);
cut();
print(a);
cout << endl;
}
return 0;
}
void input(string s, int c[]){
c[0]=s.size();
for(int i=1;i<=c[0];i++){
c[i]=s[c[0]-i]-'0';//注意减'0'
}
}
int cmp(int a[], int b[]){//比较两个数大小
if(a[0]>b[0]) return 1;
else if(a[0]<b[0]) return -1;
else{
for(int i=1;i<=a[0];i++){
if(a[i]>b[i]) return 1;
else if(a[i]<b[i]) return -1;
}
return 0;
}
}
void cut(){
if(cmp(a,b)==-1) {//如果a<b,将a,b交换,加个负号
for(int i=0;i<=b[0];i++){
swap(a[i],b[i]);
}
cout << '-';
}
if(cmp(a,b)==0) a[0]=0;
for(int i=1;i<=a[0];i++){
a[i]=a[i]-b[i];
if(a[i]<0) {
a[i]+=10;
a[i+1]--;
}
}
while(a[a[0]]==0){//检查位数,将a[0]校准
if(a[0]==0) break;
a[0]--;
}
}
void print(int c[]){
if(c[0]==0) {
cout << "0";
return;
}
for(int i=c[0];i>=1;i--) cout << c[i];
}