标签:
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
Output
For each input test, output the total amount.
Sample Input
2
3
$1.00
0
Sample Output
$11,111,111.10
顺便提醒自己写代码时要适当给注意事项注释下,本人开始注意到了不开始打“,”,后面修改代码有给忘了,然后又找了好久bug,无语了!
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
long long a[50],b[50];
char s[50],s2[50];
int main()
{
int t;
while(scanf("%d",&t),t)
{
int len,ca=0,cb=0,flag2=0;
char *c;
memset(a,0,sizeof(a)),memset(b,0,sizeof(b));
for(int i=0;i<t;i++)
{
int fa=0,k=0;
scanf("%s",s);
len=strlen(s);
int m=len;
if((c=strchr(s,‘.‘))!=NULL)//小数点出现
{
m=c-s;
flag2=1;
for(int j=m+1;j<len;j++)//b数组保留小数点后面的数,
{
b[k++]+=s[j]-‘0‘;
}
}
for(int j=m-1;j>=0;j--) //a数组保留小数点前面的数
{
if(isdigit(s[j]))
a[fa++]+=s[j]-‘0‘;
}
ca=max(ca,fa-1); //保留小数点前数的最长位置
}
if(b[1]>=10) //小数点后面的数进位
b[0]+=b[1]/10, b[1]%=10;
if(b[0]>=10)
a[0]+=b[0]/10, b[0]%=10;
for(int i=0;i<=ca;i++) //小数点前面的数进位 只保留一位数
{
if(a[i]>=10)
{
a[i+1]+=a[i]/10;
a[i]%=10;
}
}
while(a[ca+1]>0)
{
ca++;
a[ca+1]+=a[ca]/10;
a[ca]%=10;
}
int flag=1,sum=0,cnt=0;
printf("$");
for(int i=0;i<=ca;i++) //分点
{
++sum;
s2[cnt++]=a[i]+‘0‘;
if(i==ca)
continue;
if(sum==3)
{
s2[cnt++]=‘,‘;
sum=0;
}
}
s2[cnt]=0;
for(int i=cnt-1;i>=0;i--)
printf("%c",s2[i]);
printf(".");
for(int i=0;i<2;i++)
printf("%d",b[i]);
printf("\n");
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/acm__dongsheng/article/details/51366438