PAT 1001 A+B Format

2018-11-09  本文已影响0人  离山尘海

题目说明

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).

题目中文说明

输入两个整数,输出其和,要求输出标准化格式,即每三位要有一个逗号,如1,000,000里需要两个逗号

开始操作

思路很流畅,自然而然想到除法和取余数的操作,然后输出的时候记得逗号

//以下为错误答案
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
    int a, b, c;
    cin >> a>> b;
    c = a + b;
    if (abs(c) < 1000)
        cout << c;
    else
        if (abs(c) < 1000000)
            cout << c / 1000 << "," << c % 1000;
        else
            cout << c / 1000000 << "," << (c % 1000000) / 1000 << "," << (c % 1000000) % 1000;
}

错误原因

出错处在于%取余,因为我们想要的是1999%1000=999得到的后三位,而忽略了2000%1000=0,而且负数取余数后仍然带着负号,所以使用abs()函数取绝对值
于是我们需要格式化输出

正确代码

#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
int main()
{
    int a, b, c;
    cin >> a>> b;
    c = a + b;
    if (abs(c) < 1000)
        cout << c;
    else
        if (abs(c) < 1000000)
            cout << c / 1000 << "," << setw(3) << setfill('0') << abs(c % 1000);
        else
            cout << c / 1000000 << "," << setw(3) << setfill('0') << abs((c % 1000000) / 1000) << "," << setw(3) << setfill('0') << abs((c % 1000000) % 1000);
}

其他做法

有一种思路,先将计算好的数值判断正负,确定符号位,abs取绝对值后转化成字符串,通过计算字符串的长度判断位数,然后在输出的时候只需要取字符串的几位+逗号即可。不做详述。

上一篇下一篇

猜你喜欢

热点阅读