地址:
题意:中文。。。高精度正小数加法。
mark:高精度加法,如果把整数部分和小数部分分开搞,比较麻烦。定义了一个struct,数组存数字,dec存的是这个数字里末尾的多少位是小数部分的。两个小数相加,先对齐小数位(位数少的在后面补0)然后当整数加法搞!wa了一次。用宏要注意!41行和42行,如果没有加{}的话,前面的if只管一句!
代码:
1 # include2 # include 3 4 5 #define ExPand(a,b) for(i = 0 ; i < b ; i++) strcat(a->num,"0") ; a->dec+=b 6 7 8 typedef struct Real{ 9 char num[1000] ;10 int dec ;11 }Real ;12 13 14 Real r1, r2, r3 ;15 char s1[1000], s2[1000], ans[1000] ;16 17 18 int max(int a, int b){ return a>b?a:b;}19 20 21 void add(char a[], char b[], char c[])22 {23 int aa, bb, len1 = strlen(a), len2 = strlen(b), len = max(len1, len2) ;24 int i, j, k, cc = 0 ;25 c[len+1] = '\0' ;26 for (i = len1-1, j =len2-1, k = len ; i >= 0 || j >= 0 ; i--, j--, k--)27 {28 aa = (i<0 ? 0 : a[i]-'0') ;29 bb = (j<0 ? 0 : b[j]-'0') ;30 c[k] = (aa+bb+cc)%10+'0';31 cc = (aa+bb+cc)/10 ;32 }33 if (cc != 0) c[0] = cc+'0' ;34 else strcpy(c, c+1) ;35 }36 37 38 void RealAdd(Real* a, Real* b, Real* c)39 {40 int i ;41 if (a->dec < b->dec) {ExPand(a, b->dec-a->dec) ;}42 if (a->dec > b->dec) {ExPand(b, a->dec-b->dec) ;}43 c->dec = a->dec;44 add(a->num, b->num, c->num) ;45 }46 47 48 void Load(char s[], Real* real)49 {50 int i, j, c = -1 ;51 for (i = 0, j = 0; s[i] ; i++)52 if (s[i] == '.') c++ ;53 else{54 real->num[j++] = s[i] ;55 if (c != -1) c++ ;56 }57 real->num[j++] = '\0' ;58 real->dec = max(c, 0) ;59 if (real->num[0] == '\0') strcpy (real->num, "0") ;60 }61 62 63 void Set (Real *real, char s[])64 {65 int i, j ;66 int len = strlen(real->num) ;67 for (i = 0, j = -1 ; i < len-real->dec ; i++)68 {69 if (real->num[i] != '0' && j==-1) j = 0 ;70 if (j != -1) s[j++] = real->num[i] ;71 }72 if (j<=0) j = 0, s[j++] = '0' ;73 s[j++] = '.' ;74 for (i = len-real->dec ; i < len ; i++)75 s[j++] = real->num[i] ;76 s[j++] = '\0' ;77 j = strlen (s)-1 ;78 while (s[j] == '0') s[j--] = '\0' ;79 if (s[j] == '.') s[j] = '\0' ;80 }81 82 83 int main ()84 {85 while (~scanf ("%s%s", s1, s2))86 {87 Load(s1, &r1) ; Load(s2, &r2) ;88 RealAdd(&r1, &r2, &r3) ;89 Set (&r3, ans) ;90 puts (ans) ;91 }92 return 0 ;93 }