zoj2476
Description
Given a list of monetary amounts in a standard format, please calculate the total amount.
We define the format as follows:
The amount starts with ‘$’.
The amount could have a leading ‘0’ if and only if it is less then 1.
The amount ends with a decimal point and exactly 2 following digits.
The digits to the left of the decimal point are separated into groups of three by commas (a group of one or two digits may appear on the left).
Input
The input consists of multiple tests. The first line of each test contains an integer N (1 <= N <= 10000) which indicates the number of amounts. The next N lines contain N amounts. All amounts and the total amount are between
0.00and
20,000,000.00, inclusive. N=0 denotes the end of input.
Output
For each input test, output the total amount.
Sample Input
2
1,234,567.89
9,876,543.21
3
0.01
0.10
$1.00
0
Sample Output
11,111,111.10
1.11
题目意思就是多个我们常见金额的表示的那种字符串。计算出总金额;
看下数据;最坏情况就是20亿但int的范围是-21亿到21亿;因此可以先不用大数方法用字符串的处理;
先看下这种方法的大数模板
记得初始化为0;不然不会错的;memset;
aa[l] = a[j]-'0';
for (j = 0; j < 20; j++){
ans[j] = aa[j] + ans[j];
ans[j+1] += ans[j] / 10;
ans[j] = ans[j] % 10;
}
一般后面还要接着
for (j = 19; j >= 0; j--){//判断截止位置;
if (ans[j] != 0)
break;
k = j;
}
代码;
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int n, i, j, len, l,k, aa[25],ans[25],c;
char a[25],s[25];
while(scanf("%d",&n) != EOF && n != 0){
memset(ans,0,sizeof(ans));
memset(s, 0, sizeof(s));
for(i = 0; i < n; i++){
memset(aa,0,sizeof(aa));
scanf("%s",a);
len = strlen(a);
l = 0;
for(j = len-1; j >= 0; j--){//反过来了。
if(a[j]>='0'&&a[j]<='9'){
aa[l] = a[j]-'0';
l++;
}
}
for (j = 0; j < 20; j++){
ans[j] = aa[j] + ans[j];
ans[j+1] += ans[j] / 10;
ans[j] = ans[j] % 10;
}
}
for (j = 19; j >= 0; j--)
if (ans[j] != 0)
break;
k = j;
if(k < l-1){//防止前导0;
k = l-1;
}
l = 0;
for (j = 0, i = 1; j <= k; j++, i++){
s[l] = ans[j] + 48;
l++;
if (j == 1){
s[l]= '.';
l++;
i = 0;
}
if (i%3 == 0 && i != 0 && i != k-1){
s[l]= ',';
l++;
}
}
s[l]='$';
for (i=l;i>=0;i--){
putchar(s[i]);
}
printf("\n");
}
return 0 ;
}