# include <stdio.h>
# include <string.h>
#define ExPand(a,b) for(i = 0 ; i < b ; i++) strcat(a->num,"0") ; a->dec+=b
typedef struct Real{
char num[1000] ;
int dec ;
}Real ;
Real r1, r2, r3 ;
char s1[1000], s2[1000], ans[1000] ;
int max(int a, int b){return a>b?a:b;}
void add(char a[], char b[], char c[])
{
int aa, bb, len1 = strlen(a), len2 = strlen(b), len = max(len1, len2) ;
int i, j, k, cc = 0 ;
c[len+1] = '\0' ;
for (i = len1-1, j =len2-1, k = len ; i >= 0 || j >= 0 ; i--, j--, k--)
{
aa = (i<0 ? 0 : a[i]-'0') ;
bb = (j<0 ? 0 : b[j]-'0') ;
c[k] = (aa+bb+cc)%10+'0';
cc = (aa+bb+cc)/10 ;
}
if (cc != 0) c[0] = cc+'0' ;
else strcpy(c, c+1) ;
}
void RealAdd(Real* a, Real* b, Real* c)
{
int i ;
if (a->dec < b->dec) {ExPand(a, b->dec-a->dec) ;}
if (a->dec > b->dec) {ExPand(b, a->dec-b->dec) ;}
c->dec = a->dec;
add(a->num, b->num, c->num) ;
}
void Load(char s[], Real* real)
{
int i, j, c = -1 ;
for (i = 0, j = 0; s[i] ; i++)
if (s[i] == '.') c++ ;
else{
real->num[j++] = s[i] ;
if (c != -1) c++ ;
}
real->num[j++] = '\0' ;
real->dec = max(c, 0) ;
if (real->num[0] == '\0') strcpy (real->num, "0") ;
}
void Set (Real *real, char s[])
{
int i, j ;
int len = strlen(real->num) ;
for (i = 0, j = -1 ; i < len-real->dec ; i++)
{
if (real->num[i] != '0' && j==-1) j = 0 ;
if (j != -1) s[j++] = real->num[i] ;
}
if (j<=0) j = 0, s[j++] = '0' ;
s[j++] = '.' ;
for (i = len-real->dec ; i < len ; i++)
s[j++] = real->num[i] ;
s[j++] = '\0' ;
j = strlen (s)-1 ;
while (s[j] == '0') s[j--] = '\0' ;
if (s[j] == '.') s[j] = '\0' ;
}
int main ()
{
//s1+s2=ans
while (~scanf ("%s%s", s1, s2))
{
Load(s1, &r1) ;
Load(s2, &r2) ;
RealAdd(&r1,&r2,&r3) ;
Set (&r3, ans) ;
puts (ans) ;
}
return 0 ;
}
小数高精度加法
最新推荐文章于 2024-02-29 22:12:44 发布