HDU 1753 大明A+B

Problem Description
话说,经过了漫长的一个多月,小明已经成长了许多,所以他改了一个名字叫“大明”。
这时他已经不是那个只会做100以内加法的那个“小明”了,现在他甚至会任意长度的正小数的加法。
现在,给你两个正的小数A和B,你的任务是代表大明计算出A+B的值。
 
Input
本题目包含多组测试数据,请处理到文件结束。
每一组测试数据在一行里面包含两个长度不大于400的正小数A和B。
 
Output
请在一行里面输出输出A+B的值,请输出最简形式。详细要求请见Sample Output。
 
Sample Input
1.1 2.9
1.1111111111 2.3444323343
1 1.1
 
Sample Output
4
3.4555434454
2.1
 
思路:
    本题很明显是高精度加法,解决这类题方法也很多,我的方法就是,开两个1000的数组读取A和B,前五百位存整数,后五百位存小数,然后将数组倒着相加即可。

AC代码如下:

 1 #include<cstdio>
2 #include<iostream>
3 #include<cstring>
4 #define Max 1010
5
6 char str1[Max],str2[Max],ans[Max],temp1[Max],temp2[Max];
7 void Calculate()
8 {
9 int i,j,k,p,q,n,s,c;
10 memset(str1,0,sizeof(str1));
11 memset(str2,0,sizeof(str2));
12 memset(ans,0,sizeof(ans));
13 n=strlen(temp1);
14 if(strchr(temp1,'.')==NULL)
15 k=n;
16 else
17 k=strchr(temp1,'.')-temp1;
18 for(i=k-1,j=500;i>=0;i--,j++)
19 str1[j]=temp1[i]-'0';
20 for(i=k+1,j=499;i<n;i++,j--)
21 str1[j]=temp1[i]-'0';
22 n=strlen(temp2);
23 if(strchr(temp2,'.')==NULL)
24 k=n;
25 else
26 k=strchr(temp2,'.')-temp2;
27 for(i=k-1,j=500;i>=0;i--,j++)
28 str2[j]=temp2[i]-'0';
29 for(i=k+1,j=499;i<n;i++,j--)
30 str2[j]=temp2[i]-'0';
31 c=0;
32 for(i=0;i<1010;i++)
33 {
34 s=str1[i]+str2[i]+c;
35 ans[i]=s%10;
36 c=s/10;
37 }
38 return ;
39 }
40 void Output()
41 {
42 int i,j;
43 for(i=1009;i>500;i--)
44 if(ans[i])
45 break;
46 for(;i>=500;i--)
47 printf("%d",ans[i]);
48 for(j=0;j<500;j++)
49 if(ans[j])
50 break;
51 if(j!=500)
52 {
53 printf(".");
54 for(i=499;i>=j;i--)
55 printf("%d",ans[i]);
56 }
57 printf("\n");
58 }
59 int main()
60 {
61 while(~scanf("%s %s",&temp1,&temp2))
62 {
63 Calculate();
64 Output();
65 }
66 return 0;
67 }



posted @ 2012-02-17 10:03  Chnwy  阅读(930)  评论(0编辑  收藏  举报