PAT甲级-1001 A+B Format (20)(20 分)

1001 A+B Format (20)(20 分)

Calculate a + b 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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input

-1000000 9

Sample Output

 
   

-999,991

https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

思路:将整数用sprintf转为字符串,再观察逗号出现的位置规律,循环打印

//c++代码
#include <stdio.h>
#include<string.h>

int main(void)
{

//计算a+b的和,负数的话转为正数
 long long a, b, sum;
 scanf("%lld %lld", &a, &b);
 sum = a + b;
 if (sum < 0)
 {
  printf("-");
  sum = -sum;
 }

//将整数转化为字符串,并计算其长度
 char s[100];
 sprintf(s, "%lld", sum);
 int len = strlen(s), i;

/*逐个打印字符,当字符串长度<=3,不需要打印“,”号;
len-i包括下标为i的字符以及其后所有字符,若为3的倍数,则需要在打印该字符前打印“,”号。比如12,345,字符3的下标为2,其以及后面有3个字符,是3的倍数,则需要打印。又如123,456,789,字符4后面有6个字符,是3的倍数,则其前需要打印“,”。
但首位字符及其后面即使有3的倍数个字符,其前不需要打印“,”,比如123,456,字符1前面有0个字符,但我们不可以打印成 ,123,456 */
 for (i = 0; s[i] != 0; i++)
 {
  if(i != 0 && len > 3 && (len - i) % 3 == 0) printf(",");
  printf("%c", s[i]);
 }

 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值