基于类和对象的高精度算法封装
hi
这是使用类和对象的高精度计算封装实现,这能够进行面向对象的高精度计算编程。
#include<iostream> #include<cstring> using namespace std; class BIGINT{ public: int num[505]; int length; bool positive; BIGINT(string str=""){ memset(num, 0, sizeof(num)); positive = true; if(str == ""){ return; } else{ length = str.length(); for(int i = 0; i<str.length(); i++){ num[i] = str[str.length()-i-1]-'0'; } } } void show(){ if(positive == false){ cout<<"-"; } for(int i = length-1; i>=0; i--){ cout<<num[i]; } } }; int compare(BIGINT &a,BIGINT &b){ if(a.length > b.length){ return 1; } else if(a.length < b.length){ return -1; } else{ int maxlen = max(a.length,b.length); for(int i = maxlen-1; i>=0; i--){ if(a.num[i] > b.num[i]){ return 1; } else if(a.num[i] < b.num[i]){ return -1; } } return 0; } } BIGINT bigadd(BIGINT &a,BIGINT &b){ BIGINT c; int maxlen = max(a.length,b.length); //相加 for(int i = 0;i<maxlen;i++){ c.num[i] = a.num[i] + b.num[i]; } //进位 for(int i = 0;i<maxlen;i++){ if(c.num[i]>=10){ c.num[i+1] += 1; c.num[i] = c.num[i] % 10; } } //去零 if(c.num[maxlen] == 0){ c.length = maxlen; } else{ c.length = maxlen + 1; } return c; } BIGINT bigminus(BIGINT &a,BIGINT &b){ BIGINT c; int maxlen = max(a.length,b.length); //判断 int maxint = compare(a,b); if(maxint == 1){ //相减 for(int i = 0;i<a.length;i++){ if(a.num[i]>=b.num[i]){ c.num[i] = a.num[i] - b.num[i]; } else{ a.num[i+1] -= 1; a.num[i] += 10; c.num[i] = a.num[i] - b.num[i]; } } } else if(maxint == -1){ c = bigminus(b,a); c.positive = false; } //去零 for(int i = maxlen+1;i>=0;i--){ if(c.num[i] != 0){ c.length = i+1; return c; } } c.length = 1; return c; } BIGINT bigmultiply(BIGINT &a,BIGINT &b){ BIGINT c; //相乘 for(int i = 0;i<a.length;i++){ for(int j = 0;j<b.length;j++){ c.num[i+j] += a.num[i]*b.num[j]; c.num[i+j+1] += c.num[i+j]/10; c.num[i+j] %= 10; } } //预估 int len = a.length + b.length; //去零 for(int i = len+1;i>=0;i--){ if(c.num[i] != 0){ c.length = i+1; return c; } } c.length = 1; return c; } BIGINT bigmultiplywithsmall(BIGINT a,int b){ //相乘 for(int i = 0;i<a.length;i++){ a.num[i] *= b; } //进位 for(int i = 0;i<a.length+1;i++){ if(a.num[i]>=10){ a.num[i+1] += a.num[i] / 10; a.num[i] %= 10; } } //去零 if(a.num[a.length] != 0){ a.length += 1; } return a; } int main(){ BIGINT a("111111111"); BIGINT b("111111111"); BIGINT tmp; tmp = bigadd(a,b); cout<<"高精度加法:"; tmp.show(); cout<<endl; tmp = bigminus(a,b); cout<<"高精度减法:"; tmp.show(); cout<<endl; tmp = bigmultiply(a,b); cout<<"高精度乘法:"; tmp.show(); cout<<endl; tmp = bigmultiplywithsmall(a,100); cout<<"高低精乘法:"; tmp.show(); cout<<endl; }