PAT (Advanced Level) Practice 1001 A+B format(20)

1001. A+B Format (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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


问题的要求很简单,就不进行翻译了。个人认为这个问题的考点在于“,“的输出设计,先贴代码:

C语言

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void print(long a, long b)
{
 
long c = a + b;
 
if (c < 0)
  {
    printf(
"-");
  }
 
if (c == 0)
  {
    printf(
"0");
  }
 
long num = abs(c);
 
long count = 0;
 
int arr[7];
 
while (c)
  {
    arr[count] = c %
10;
    c = c /
10;
    count++;
  }
 
int m;
  m = count %
3;
 
int i, j = m - 1, k, n = 0;
 
for (i = 0; i < m; i++)
  {
    printf(
"%d", abs(arr[count - i - 1]));
   
if (i == m - 1 && (count - 1 - i != 0))
    {
      printf(
",");
    }
  }
 
for (i = m; i < count; i++)
  {
    k = count - i -
1;
    printf(
"%d", abs(arr[k]));
    n++;
   
if (n == 3 && k != 0)
    {
      printf(
",");
      n =
0;
    }

  }
}

int main()
{
 
long a, b;
  scanf(
"%ld %ld", &a, &b);
  print(a, b);
 
return 0;
}

说一下思路吧。print函数的参数a,b是题目中要求相加的两个数,用long长整形进行保存。在print函数中首先判断两个数之和c的符号,利用if语句对c为负是添加符号和c为零时直接输出零进行分类,然后再进行添加“,”的操作。

       根据题干中对Input的要求(-1000000 <= a, b <= 1000000),那么相加的结果最大的位数是七位,所以定义了一个元素最大个数为7的数组来储存结果中的每一位数,利用while循环将结果的每一位数保存到数组中,并求出结果的位数。

       将位数对3取余,然后从左到右添加","。先输出余数个个数的结果位数,然后输出“,“,然后按规则每三位数输出一个","即可。

猜你喜欢

转载自blog.csdn.net/qq_36163296/article/details/80240306