大数加法:int,long long 的数量级分别为 1e9,1e18,当数据大于18位时无法直接简单的a+b计算,会变成负数。
这里就要用数组来模拟俩个数相加。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char str1[505],str2[505];
int a[505],b[505],c[505];
int main() {
scanf("%s%s",str1,str2);
int i,la,lb;
la = strlen(str1);
lb = strlen(str2);
for(i=0;i<la;i++)
{
a[la-i] = str1[i] - '0';//字符转化为数字
}
for(i=0;i<lb;i++)
{
b[lb-i] = str2[i] - '0';
}
int lc = max(la,lb)+1; //可能最后一位进位(如果不进,后面要消去)
for(i=1;i<=lc;i++)
{
c[i] += a[i] + b[i] ;
c[i+1] +=c[i]/10;
c[i] = c[i]%10;
}
if(c[lc]==0&&lc>1) lc--;//if c[i] 等同于指向最大位,判断是否为0(要判断是否就是0,所以有lc>0)
for(i=0;i<lc;i++)
{
printf("%d",c[lc-i]);
}
return 0;
}大数减法
差不多相同的道理,只是变成与更大位数借位,这个一换,就成就了减法;
上代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int a[505],b[505],c[505];
char st1[505],st2[505],st3[505];
bool compare(char s1[], char s2[])
{
int x = strlen(s1);
int y = strlen(s2);
if(x!=y) return x>y;
else{
int i;
for(i=0;i<x;i++)
if(s1[i]!=s2[i])
return s1[i]>s2[i];
}
}
int main() {
int flag = 0;
scanf("%s%s",st1,st2);
int i,j;
if(!compare(st1,st2))
{
flag = 1;
strcpy(st3,st1);
strcpy(st1,st2);
strcpy(st2,st3);
}
int x = strlen(st1);
int y = strlen(st2);
for(i=0;i<x;i++)
a[x-i] = st1[i] - '0';
for(i=0;i<y;i++)
b[y-i] = st2[i] - '0';
int z = x;
for(i=1;i<=z;i++)
{
if(a[i]<b[i])
{
printf("zcx");
a[i]+=10;
a[i+1] -=1;
}
c[i] = a[i] - b[i];
}
while(c[z]==0&& z>1) z--;
if(flag) printf("-");
for(i=z;i>0;i--)
printf("%d",c[i]);
return 0;
}


京公网安备 11010502036488号