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;
}

猜你喜欢

转载自blog.csdn.net/yeziand01/article/details/80715495