c语言1001 字符串连接,PAT Advanced 1001. A+B Format (20) (C语言实现)

我的PAT系列文章更新重心已移至Github,欢迎来看PAT题解的小伙伴请到Github Pages浏览最新内容。此处文章目前已更新至与Github Pages同步。欢迎star我的repo。

题目

Calculate

math?formula=a%20%2B%20b and output the sum in standard format -- that is, the digits

must be separated into groups of three by commas (unless there are less than

four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers

math?formula=a and

math?formula=b where

math?formula=-10%5E6%20%5Cle%20a%2C%20b%20%5Cle%2010%5E6 . The numbers are separated by a

space.

Output Specification:

For each test case, you should output the sum of

math?formula=a and

math?formula=b in one line. The

sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

思路

2018/1/5更新0:重要参考链接

Stack overflow有一个帖子专门讨论如何做这个事情,我自己想到的三个也都是问题里几个高票答案的方法,大家可以学习一下。

两个要点:

两数和为0时要输出0;

注意逗号的输出位置,如不要在数字前面和后面有输出

2018/1/5更新1:

又看了一遍题,总感觉之前的代码太繁琐,就改了一个方法,使用字符串处理。

得到a和b后,将两者之和输入到一个字符串中去,使用sprintf函数。

只需要从后向前,每三个数字判断一下是否需要加逗号即可。

2018/1/5更新2:

还有一种更省事的方法,甚至C语言里都有直接的方法处理这种事情。那就是头文件,这个头文件可以处理不同地区或者语言的输出方式,其中就有对数字的处理。具体细节可查看相关资料,代码放在下面

#include

#include

int main(void)

{

setlocale(LC_NUMERIC, "");

printf("%'d\n", 1123456789);

return 0;

}

代码

#include

#include

int main()

{

int a, b, pos;

char num[11];

scanf("%d%d", &a, &b);

sprintf(num, "%d", a + b);

for(pos = strlen(num) - 3; pos > 0 && num[pos - 1] != '-'; pos -= 3)

{

memmove(num + pos + 1, num + pos, strlen(num) - pos + 1);

num[pos] = ',';

}

puts(num);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值