Hdu 1753 大明A+B <高精度小数相加>

题意:

很长很长的小数相加..

思路:

用1000长的数组处理两个小数..前500存整数..后500存小数..然后相应位相加..

然后输出除去前导0和后面0的..

Tips:

※ strchr(char *a, char c) 返回的是 a 字符数组中 c 字符的第一次出现的位置..返回的不是迭代器的位置..而是地址..

※ 主要就是对字符串的处理..要很小心阿..

※ 以字符数组的形式读入高精度小数..然后用他们 - ‘0’..把字符变成整数来处理..最后以整数方式输出..

Code:

View Code
 1 #include <stdio.h>
 2 #include <cstring>
 3 #define Max 1010
 4 #define clr(x) memset(x, 0, sizeof(x))
 5 
 6 char str1[Max], str2[Max], ans[Max];
 7 char tmp1[Max], tmp2[Max];
 8 
 9 void Calculate()
10 {
11     int i, j, k;
12     clr(tmp1), clr(tmp2), clr(ans);
13 
14     int len = strlen(str1);
15     if(strchr(str1, '.') == NULL)
16         k = len;
17     else
18         k = strchr(str1, '.') - str1;///--->>!!!
19     for(i = k-1, j = 500; i >= 0; --i, ++j)
20         tmp1[j] = str1[i]-'0';
21     for(i = k+1, j = 499; i < len; ++i, --j)
22         tmp1[j] = str1[i]-'0';
23 
24     len = strlen(str2);
25     if(strchr(str2, '.') == NULL)
26         k = len;
27     else
28         k = strchr(str2, '.') - str2;
29     for(i = k-1, j = 500; i >= 0; --i, ++j)
30         tmp2[j] = str2[i] - '0';
31     for(i = k+1, j = 499; i < len; ++i, --j)
32         tmp2[j] = str2[i] - '0';
33 
34     int tmpc = 0, tmps;
35     for(i = 0; i < 1010; ++i){
36         tmps = tmp1[i]+tmp2[i]+tmpc;
37         ans[i] = tmps%10;
38         tmpc = tmps/10;
39     }
40 }
41 
42 void outPut()
43 {
44     int i, j;
45     for(i = 1009; i > 500; --i)
46         if(ans[i]) break;
47     while(i >= 500)
48         printf("%d", ans[i--]);
49     for(j = 0; j < 500; ++j)
50         if(ans[j]) break;
51     if(j != 500){
52         printf(".");
53         for(i = 499; i >= j; --i)
54             printf("%d", ans[i]);
55     }
56     puts("");
57 }
58 
59 int main()
60 {
61     int i, j, k;
62     while(scanf("%s %s", &str1, &str2) != EOF)
63     {
64         Calculate();
65         outPut();
66     }
67     return 0;
68 }
原文地址:https://www.cnblogs.com/Griselda/p/2625948.html