大数相加
发布日期:2021-06-29 11:10:14 浏览次数:3 分类:技术文章

本文共 2646 字,大约阅读时间需要 8 分钟。

zoj2476

Description

Given a list of monetary amounts in a standard format, please calculate the total amount.

We define the format as follows:

  1. The amount starts with ‘$’.

  2. The amount could have a leading ‘0’ if and only if it is less then 1.

  3. The amount ends with a decimal point and exactly 2 following digits.

  4. 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
#include
#include
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 ;}

转载地址:https://blog.csdn.net/zw1996/article/details/51377311 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:sort之结构体排序2
下一篇:数组名及数组名的地址(还有一个小问题没解决)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月25日 06时02分27秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章