高精度四则运算---加减

#include <iostream>
using namespace std;
#define MAXLEN 1000
int *Str2Int(char *);
char *Int2Str(int *,int);
int Check(int *,int);
char *addition(char *s1,char *s2);
char *substract(char *s1,char *s2);

int main(){
   char s1[MAXLEN],s2[MAXLEN]; //accept two numbers
   while(cin >> s1 >> s2){
   cout << addition(s1,s2) << endl;
   cout << substract(s1,s2) << endl;
   return 0;
}
}
// translate character  string type into integer type number
int *Str2Int(char *str){ 
   int len = strlen(str);
   int i;
   int *t = new int[(len + 1) * sizeof(int)];
   for(i = 0; i < len; ++i)
    t[i] = str[len - 1- i] - '0';
    return t;
}
//trans int* into char *
char *Int2Str(int *num,int n){
     char *s = new char[(n + 1) * sizeof(char)];
     int i;
	 for(i = 0; i < n; ++i)
	   s[i] = (char)num[n - 1 - i] + 48;
	   s[i] = '\0';
	   return s;	
}
//归整算法,进位处理 
int Check(int *num,int n){
    int len = n,i;
	while(num[len - 1] == 0 && len > 1) len--;
	for(i = 0; i < len; ++i)
	 if(num[i] >= 10){
	    num[i + 1] = num[i + 1] + num[i] / 10;
	    num[i] %= 10;
	 }
	 if(num[i] != 0) len = i + 1;
	 return len;
}

char *addition(char *s1,char *s2){
   int len1 = strlen(s1);
   int len2 = strlen(s2);
   int len = len1 >= len2 ? len1 : len2;
   int *t1 = new int[(len + 2) * sizeof(int)];
   int *t2 = new int[(len + 2) * sizeof(int)];
   t1 = Str2Int(s1);
   t2 = Str2Int(s2);
   int i;
   for(i = len1; i < len + 1; ++i) t1[i] = 0; //缺位前补0 
   for(i = len2; i < len + 1; ++i) t2[i] = 0;
   for(i = 0; i < len; ++i) t1[i] += t2[i];
   len = Check(t1,len);
   return Int2Str(t1,len);
}

char *substract(char *s1,char *s2){
   int len1 = strlen(s1);
   int len2 = strlen(s2);
   int len = len1 >= len2 ? len1 : len2;
   int i,c,cf;
   c = cf = 0;
   char *tmp = new char[(len + 2) * sizeof(char)];
   char *csub = new char[(len + 3) * sizeof(char)];
   if((len1 < len2) || (len1 == len2 && strcmp(s1,s2) < 0)){ //被除数小于除数 
   	strcpy(tmp,s1);
   	strcpy(s1,s2);
   	strcpy(s2,tmp);
   	len1 = strlen(s1);
   	len2 = strlen(s2);
   	cf = 1; //是负数 
   }
   int *t1 = new int[(len + 2) * sizeof(int)];
   int *t2 = new int[(len + 2) * sizeof(int)];
   t1 = Str2Int(s1);
   t2 = Str2Int(s2);
   for(i = len1; i < len; ++i) t1[i] = 0;//消除前置0
   for(i = len1; i < len; ++i) t2[i] = 0;
   for(i = 0; i < len; ++i){
   	if(t1[i] >= t2[i]) t1[i] -= t2[i];
   	else{  //t1[i] = t1[i] + 10 - t2[i];   t1[i + 1] -= 1;
   	 t1[i] -= t2[i];
	 c = t1[i] * (-1) / 10 + 1;	
	 t1[i] = t1[i] + 10 * c;
	 t1[i + 1] -= c;
   	}
   }
   int n = i,begin = 0;
   while(t1[n - 1] == 0 && n > 1) n--; //消除缺位的0
   if(cf == 1){
   	csub[0] = '-';
   	n++;
   	begin = 1;
   }
   for(i = begin; i < n; ++i)
    csub[i] = (char)t1[n - 1 - i] + 48; 	
    csub[i] = '\0'; //一定不要忘加
    return csub;
}

 

你可能感兴趣的:(高精度四则运算---加减)