PAT 1001 A+B Format

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

-999,991

Sample Output

-1000000 9

第一遍代码如下

#include <stdio.h>
#include <math.h>
int main()
 {
  int a,b,sum,c;
  printf("input a and b:");
  scanf("%d%d",&a,&b);
  sum=a+b;
  c=abs(sum);
  if(abs(sum)>=1000000)
  printf("%d,%d,%d",sum/1000000,(c/1000)%1000,c%1000);
  else if(abs(sum)>=1000)
  printf("%d,%d",sum/1000,c%1000);
  else
  printf("%d",sum);
  return 0;
}

发现:测试数据时,例如输入1000 8,输出数据为1,8.没有补上0.

修改:

#include <stdio.h>
#include <math.h>
int main()
 {
  int a,b,sum,c;
  printf("input a and b:");
  scanf("%d%d",&a,&b);
  sum=a+b;
  c=abs(sum);
  if(abs(sum)>=1000000)
  printf("%d,%03d,%03d",sum/1000000,(c/1000)%1000,c%1000);
  else if(abs(sum)>=1000)
  printf("%d,%03d",sum/1000,c%1000);
  else
  printf("%d",sum);
  return 0;
}

测试几组数据后发现结果无误,上传PAT,发现错误如下:

a.c: In function ‘main’:
a.c:9:5: warning: implicit declaration of function ‘abs’ [-Wimplicit-function-declaration]
   c=abs(sum);
     ^~~
a.c:7:3: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
   scanf("%d %d",&a,&b);
   ^~~~~~~~~~~~~~~~~~~~

发现:题目中没有要求输出“input a and b".代码中多出了printf("input a and b");这一句,导致结果错误.删除后结果正确.

修改:

#include <stdio.h>
#include <math.h>
int main()
 {
  int a,b,sum,c;
  scanf("%d%d",&a,&b);
  sum=a+b;
  c=abs(sum);
  if(abs(sum)>=1000000)
  printf("%d,%03d,%03d",sum/1000000,(c/1000)%1000,c%1000);
  else if(abs(sum)>=1000)
  printf("%d,%03d",sum/1000,c%1000);
  else
  printf("%d",sum);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42776479/article/details/81175536
今日推荐