PAT-A1001 A+B Format 题目内容及题解

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 Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10^​6​​≤a,b≤10​^6​​. The numbers are separated by a space.

Output Specification:

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

题目大意

题目给出两个数,计算其和并将其按照规定格式输出。

解题思路

  1. 读入数据,并计算;
  2. 判断正负,并修正数据为非负数;
  3. 用栈的方式每三位数存储一次(此处需注意如初始为0也要有输出);
  4. 将此栈按照格式输出并返回0值。

代码

#include<stdio.h>
int main(){
    int a,b,ans;
    int num[5];
    int k=0;
    scanf("%d%d",&a,&b);
    ans=a+b;
    if(ans<0){
        printf("-");
        ans=-ans; 
    }
    do{
        num[k++]=ans%1000;
        ans/=1000;
    }while(ans);
        printf("%d",num[--k]);
    while(k>0){
        printf(",%03d",num[--k]);
    }
    printf("\n");
    return 0;
} 

运行结果

PAT-A1001 A+B Format 题目内容及题解