#include <iostream.h>#include <mem.h>const int MAXSIZE = 20; //max length of the numberconst int K = 2; //baniry system 在这里可以修改K进制的高精度class hp{ int len; //length of number int s[MAXSIZE]; //store high precistion number public: hp(); hp hp::operator = (hp C);};hp::hp(){ len = 0; memset(s, 0, MAXSIZE*sizeof(int));}istream &operator >> (istream &in, hp &HP){ char s[MAXSIZE]; int i; cout << "Input Number = "; cin >> s; HP.len = strlen(s); for (i = 0; i < HP.len; i++) HP.s[i] = s[HP.len-i-1] - '0'; //change string to high precisition return in;}ostream &operator << (ostream &out, hp &HP){ int i; for (i = HP.len-1; i >= 0; i--) cout << HP.s[i]; return out;}hp operator +(hp A, hp B){ int i, len; hp C; if (A.len > B.len) len = A.len; else len = B.len; //get the bigger length of A,B for (i = 0; i < len; i++){ C.s[i] += A.s[i] + B.s[i]; if (C.s[i] >= K){ C.s[i] -= K; ++C.s[i+1]; //add 1 to a higher position } } if (C.s[len] > 0) C.len = len+1; else C.len = len; return C;}hp operator - (hp A, hp B) //different of the two HighPrecision Numbers{ int len, i; hp C; if (A.len > B.len) len = A.len; else len = B.len;C.len = 4; for (i = 0; i < len; i++){ C.s[i] += A.s[i] - B.s[i]; if (C.s[i] < 0){ C.s[i] += K; --C.s[i+1]; //subtract 1 to higher position } } while (C.s[len-1] == 0 && len > 1) --len; C.len = len; return C;}hp operator * (const hp &A, const hp &B){ int len, i, j; hp C; for (i = 0; i < A.len; i++) for (j = 0; j < B.len; j++){ len = i+j; C.s[len] += A.s[i] * B.s[j]; C.s[len+1] += C.s[len] / K; C.s[len] %= K; } len = A.len + B.len + 1; /* the product of a number with i digits and a number with j digits can only have at most i+j+1 digits*/ while (len > 1 && C.s[len-1] == 0) --len; C.len = len; return C;}hp hp::operator = (hp C){ int i; len = C.len; for (i = 0; i < MAXSIZE; i++) s[i] = C.s[i]; return *this;}int main(){ hp A, B, C; cin >> A >> B; C = A+B; cout << A << ‘+’ << B << “ = “ << C << endl; C = A-B; cout << A << ‘-’ << B << “ = “ << C << endl; C = A*B; cout << A << '*' << B << " = " << C << endl; return 0; }

评论