EchoDemo's Blogs

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 -1000000 <= a, b <= 1000000. 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

此题使用如下代码在PAT测试时出现一个段错误。如有大佬光临寒舍,还望多多指教。

#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
#include<stack>
using namespace std;


int main() {
    int a, b,sum=0;
    cin >> a >> b;
    sum = a + b;
    if (sum < 0) cout << "-";//和为负数,就先把负号输出
    sum = (sum < 0) ? -sum : sum;//求绝对值

    stack<char> s;
    int num = 0;
    while (sum) {
        s.push((sum % 10)+'0');//从最低位开始入栈
        num++;//统计sum中各个位入栈的个数
        if (num % 3 == 0) s.push(',');//每当sum的位入栈三次,就把‘,’入栈
        sum /= 10;
    }

    if (s.top() == ',') s.pop();//如果全栈最顶为‘,’,则直接出栈

    while (!s.empty()) {
        cout << s.top();//输出栈顶元素
        s.pop();//栈顶元素出栈
    }
    system("pause");
    return 0;
}
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------