【C++】C++高精度加减乘除模板

利用重载运算符

我对拍过了,请大家放心使用。

#pragma GCC optimize(3,"Ofast","inline")
#pragma G++ optimize(3,"Ofast","inline")

#include 
#include 
#include 
#include 
#include 

#define R                  register int
#define re(i,a,b)          for(R i=a; i<=b; i++)
#define ms(i,a)            memset(a,i,sizeof(a))

using namespace std;

char s[505];

struct bignum {
    int l;
    int x[1005];
    void clear () {
        l=0;
        memset(x,0,sizeof(x));
    }
    void init (int v) {
        clear();
        while (v) {
            x[++l]=v%10;
            v/=10;
        }
    }
};
 
bignum a,b,d;
 
void writeln (bignum x) {
    for (int i=x.l; i>=1; i--) printf("%d",x.x[i]);
    printf("\n");
}
 
void change (bignum &a,bignum &b) {
    bignum t;
    t=a;
    a=b;
    b=t;
}
 
bool operator <= (bignum a,bignum b) {
    if (a.lb.l) return 0;
    for (int i=a.l; i>=1; i--) 
        if (a.x[i]b.x[i]) return 0;
    return 1;
}
 
bignum operator + (bignum a,bignum b) {
    int maxl=max(a.l,b.l);
    bignum c;
    c.clear();
    for (int i=1; i<=maxl; i++) {
        c.x[i]=a.x[i]+b.x[i]+c.x[i-1]/10;
        c.x[i-1]%=10;
    }
    c.l=maxl;
    while (c.x[c.l]>=10) {
        c.l++;
        c.x[c.l]=c.x[c.l-1]/10;
        c.x[c.l-1]%=10;
    }
    return c;
}
 
bignum operator - (bignum a,bignum b) {
    bignum c;
    c.clear();
    for (int i=1; i<=a.l; i++) {
        c.x[i]=a.x[i]-b.x[i];
        if (c.x[i]<0) {
            c.x[i]+=10;
            a.x[i+1]--;
        }
    }
    c.l=a.l;
    while (c.x[c.l]==0 && c.l>1) c.l--;
    return c;
}
 
bignum operator * (bignum a,bignum b) {
    bignum c;
    c.clear();
    for (int i=1; i<=a.l; i++) 
        for (int j=1; j<=b.l; j++) {
            c.x[i+j-1]+=a.x[i]*b.x[j]+c.x[i+j-2]/10;
            c.x[i+j-2]%=10;
        }
    c.l=a.l+b.l-1;
    while (c.x[c.l]==0 && c.l>1) c.l--;
    while (c.x[c.l]>=10) {
        c.l++;
        c.x[c.l]=c.x[c.l-1]/10;
        c.x[c.l-1]%=10;
    }
    return c;
}
 
bignum operator / (bignum a,bignum b) {
    bignum p,ten,t,x,c;
    c.clear();
    ten.init(10);
    for (int i=a.l; i>=1; i--) {
        t.init(a.x[i]);
        p=p*ten+t;
        for (int j=9; j>=0; j--) {
            x.init(j);
            if (b*x<=p) {
                c.x[i]=j;
                p=p-b*x;
                break;
            }
        }
    }
    c.l=a.l;
    while (c.x[c.l]==0 && c.l>1) c.l--;
    return c;
}

int main () {
    scanf("%s",s);
    a.l=strlen(s);
    for (int i=0; i> ch;
    if (ch=='+') d=a+b;
    if (ch=='-') d=a-b;
    if (ch=='*') d=a*b;
    if (ch=='/') d=a/b;
    writeln(d);
    return 0;
}

 

你可能感兴趣的:(#,C++,Code,#,C)