高精度加减乘除(全)

#include
#include 
#include 
using namespace std;
struct bign{//大整数数据类型
    int d[1000];
    int len;
    bign(){
        memset(d,0,sizeof(d));
        len = 0;
    }
};
//转换函数
bign change(char a[]){
    bign ans;
    ans.len = strlen(a);
    for (int i = 0; i < strlen(a); ++i) {
        ans.d[i] = a[strlen(a) - i -1] - '0';
    }
    return ans;
}
bign add(bign a,bign b){
    bign ans;
    ans.len = 0;
    int carry = 0;//进位
    for(int i = 0; i < a.len || i < b.len; i++){
        int temp = a.d[i] + b.d[i] + carry;
        ans.d[ans.len++] = temp % 10;
        carry = temp / 10;
    }
    if (carry != 0){
        ans.d[ans.len++] = carry;
    }
    return ans;
}
bign sub(bign a,bign b){
    bign ans;
    for (int i = 0; i < a.len|| i < b.len; ++i) {
        if (a.d[i] < b.d[i]){
            a.d[i + 1] --;//进位
            a.d[i] += 10;
        }
        ans.d[ans.len++] = a.d[i] - b.d[i];
    }
    while(ans.len - 1 >= 1 && ans.d[ans.len - 1] == 0){
        ans.len--;//去除最高位的零
    }
    return ans;
}
bign multi(bign a,int b){
    bign ans;
    int carry = 0;//进位
    for (int i = 0; i < a.len; ++i) {
        int temp = a.d[i] * b + carry;
        ans.d[ans.len++] = temp % 10;
        carry = temp / 10;
    }
    while(carry != 0){//乘法的进位不止一位
        ans.d[ans.len++] = carry % 10;
        carry /= 10;
    }
    return ans;
}
bign divide(bign a,int b,int &r){
    bign ans;
    ans.len = a.len;
    for (int i = a.len - 1; i >= 0; --i) {
        r = r*10 + a.d[i];
        if (r < b) ans.d[i] = 0;
        else{
            ans.d[i] = r/b;
            r = r % b;
        }
    }
    while(ans.len - 1 >= 1 && ans.d[ans.len - 1] ==0){
        ans.len--;
    }
    return ans;
}
void print(bign a){
    for (int i = a.len - 1; i >= 0; --i) {
        cout<<a.d[i];
    }
    cout<<endl;
}

int main() {
    char str1[1000],str2[1000];
    cin>>str1>>str2;
    bign a = change(str1);
    bign b = change(str2);
    bign c = add(a,b);
    print(c);
    c = sub(a,b);
    print(c);
    c = multi(a,5);
    print(c);
    int r = 0;
    c = divide(a,7,r);
    print(c);
    return 0;
}

你可能感兴趣的:(c++,算法)