A+B 高精度

        在C++中有四种运算符:+,-,*,/,%。当你要执行一个超过int,或long long型的数时,你会发现程序上限炸了,所以为了解决这个问题,我们用高精度算法。

高静度,就是把两个数通过计算机模拟生活中我们手算加法,像列竖式一样。(PS:如果您不会竖式,那您就去百度普及一下吧,T_T)。

       

      那么我们分别用数组a,b分别存储加数和被加数,用c存储结果。

因此,代码如下:

#include<bits/stdc++.h>
using namespace std;
int x[110000],y[110000],c[11000000];
char str1[110000],str2[110000];
int n1,n2;
int main()
{
    memset(x,0,sizeof(x));//置空数组x,y,c 
    memset(y,0,sizeof(y));
    memset(c,0,sizeof(c));
    cin>>str1;//读入加数 
    cin>>str2;//读入被加数 
    n1=strlen(str1);//长度 
    n2=strlen(str2);
    int lena=n1;
    int lenb=n2;
    int jw=0;
    for(int i=0;i<lena;i++) x[i]=str1[lena-1-i]-'0';//倒序存储 
    for(int i=0;i<lenb;i++) y[i]=str2[lenb-1-i]-'0';
    int len=max(lena,lenb);//为了防止出现漏项 
    for(int i=0;i<len;i++)
    {
        c[i]=x[i]+y[i]+jw;//jw为进位
        jw=c[i]/10; 
        c[i]%=10;//为了防止出现重复加操作 
    }
    if(jw==1) cout<<1;//如果进位为1,那么就输出1 
    for(int i=len-1;i>=0;i--) cout<<c[i];
}

  

猜你喜欢

转载自www.cnblogs.com/dai-jia-ye/p/9258916.html