PAT甲级1001. A+B Format(20)

来源:互联网 发布:ubuntu 麒麟wineqq 编辑:程序博客网 时间:2024/04/28 08:38

报了9.11的PAT,今天开始刷题啦。甲级一共115题。离考试还有60天,每天刷至少3题,在这里解题打卡。1001还是很简单的,然而好久不练有点生疏。

题目描述

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

解题代码

#include "stdio.h"#include "stdlib.h"#include <stack>using namespace std;int getNumber();int main(){    stack<int> output;    int num1=0, num2=0, sum;    scanf("%d %d", &num1, &num2);    sum = num1 + num2;    if (sum / 1000 == 0) {        printf("%d",sum);    }    else {        if (sum < 0) {            printf("-");            sum = -sum;        }        while (sum) {            output.push(sum % 1000);            sum = sum / 1000;        }        //先输出最高的1-3位,因为格式控制符不一样,这里不一定要补全3位        printf("%d", output.top());        output.pop();        //再输出剩下的        while (!output.empty())        {                      printf(",%03d", output.top());            output.pop();        }    }    return 0;}
0 0
原创粉丝点击