菜鸡一个,从现在起养成写博客的习惯,不要每天把杂七杂八的东西只记在txt里面

下面时一个高精度的模板供大家使用,方便做题

/*
Date : 2015-8-21 晚上
Author : ITAK

Motto :

今日的我要超越昨日的我,明日的我要胜过今日的我;
以创作出更好的代码为目标,不断地超越自己。
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
/**
如何用:
1、变量声明:可以给初值,如:BigInt ans=100;
             可以不给初值(默认为0),如BigInt ans;
2、计算:可以连个BigInt对象相乘,相加;ans+ans*ans;
         也可以和整数相乘相加,如:ans+78*ans;
*/


struct BigInt
{
    const static int mod = 10000;
    const static int DLEN = 4;
    int a[600],len;
    BigInt()//把里面的数组初始化为1
    {
        memset(a,0,sizeof(a));
        len = 1;
    }
    BigInt(int v)//存入的整数转化为数组形式
    {
        memset(a,0,sizeof(a));
        len = 0;
        do
        {
            a[len++] = v%mod;
            v /= mod;
        }
        while(v);
    }
    BigInt(const char *s)//字符串转数组
    {
        memset(a,0,sizeof(a));
        int L = strlen(s);
        len = L/DLEN;
        if(L%DLEN)
            len++;
        int index = 0;
        for(int i=L-1; i>=0; i-=DLEN)
        {
            int t = 0;
            int k = i-DLEN+1;
            if(k<0)
                k = 0;
            for(int j=k; j<=i; j++)
                t = t*10+s[j]-'0';
            a[index++] = t;
        }
    }
    BigInt operator +(const BigInt &b)const
    {
        BigInt res;
        res.len = max(len,b.len);
        for(int i=0; i<=res.len; i++)
        {
            res.a[i] = 0;
        }
        for(int i=0; i<res.len; i++)
        {
            res.a[i] += ((i<len)?a[i]:0)+((i<b.len)?b.a[i]:0);
            res.a[i+1] += res.a[i]/mod;
            res.a[i] %= mod;
        }
        if(res.a[res.len]>0)
            res.len++;
        return res;
    }
    BigInt operator *(const BigInt &b)const
    {
        BigInt res;
        for(int i=0; i<len; i++)
        {
            int up = 0;
            for(int j=0; j<b.len; j++)
            {
                int temp = a[i]*b.a[j]+res.a[i+j]+up;
                res.a[i+j] = temp%mod;
                up = temp/mod;
            }
            if(up != 0)
                res.a[i+b.len] = up;
        }
        res.len = len+b.len;
        while(res.a[res.len-1]==0 && res.len>1)res.len--;
        return res;
    }
    void output()
    {
        printf("%d",a[len-1]);
        for(int i=len-2; i>=0; i--)
            printf("%04d",a[i]);
        printf("\n");
    }
};

int main(int argc, char const *argv[]) {
//
// BigInt a=132433423,b=243637536;//精度10的9次方
// BigInt ans=a+b;
// BigInt res=a*b;
char aa[10000];
char bb[1000000];
cin>>aa>>bb;
BigInt a1=aa,b1=bb;
BigInt ans1=a1+b1;
BigInt ans2=a1*b1;
ans1.output();
ans2.output();
  // ans.output();
  // res.output();//乘法

  return 0;
}

高精度计算

相关文章:

  • 2020-04-16
  • 2021-06-06
  • 2021-11-14
  • 2021-09-21
  • 2019-07-16
  • 2020-01-28
  • 2021-04-08
猜你喜欢
  • 2021-09-14
  • 2021-10-01
  • 2019-03-20
  • 2021-11-21
  • 2021-11-19
相关资源
相似解决方案