P1001 A+B Format

转跳点:🐏

1001 A+B Format (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 Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where 106​​a,b106. 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
  这道题的意思是,将A+B 两个数相加,且 A B两个数 限制为 −106​​,b10,然后按照国际标准给数字填上,我偷了个懒, A, B整型输入, 和存储在字符串里,然后%c一个个输出
这里需要注意几个输出点:
  1.   最后一位,不需要判断
  2.   如果和小于0,那么需要跳过‘-’
  3.   注意数组大小,记得考虑进位和‘\0’以及‘-’

AC代码如下:

106​​≤a,b≤106#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char str[9];
    int A, B;

    scanf("%d %d", &A, &B);
    sprintf(str, "%d", (A + B));
    int len = strlen(str);

    for (int i = 0; i < len; i++)
    {
        printf("%c", str[i]);
        if (len - 1 == i || '-' == str[i])
        {
            continue;
        }
        if (0 == (len - 1 - i) % 3)
        {
            printf(",");
        }
    }

    return 0;
}

 

C++版本:

  我找到了一个库<sstream>这个库实现了sprintf的功能比sprintf更加安全具体使用方法,看这篇博客U•ェ•*U

#include <iostream>
#include <sstream>
 
using namespace std;
 
int main()
{
    int A, B;
    cin >> A >> B;
    
    stringstream sStream;
    sStream << A + B;           //将A+B的和放入stringstream的缓存区域
    string s(sStream.str());    //将sStream里的值按照某种数据格式写入s里
    //这个过程类似于sprintf()
 
    int cnt = 0;
    for (string::iterator it = s.end() - 1; it != s.begin(); --it)
    {//string内置的迭代器
        (++cnt) %= 3;
        if (cnt == 0 && !((it - s.begin() == 1) && s.front() == '-'))
        {
            s.insert(it, ',');
        }
    }
            
    cout << s << endl;
 
    return 0;
}

 

更新:2020-02-18 14:12:18

  最近在学Python,思考了一波,嗯,python大法好啊,不过我还是热衷于C/C++

a, b = map(int, input().split())   #format函数
print(format(a+b, ','))        #format函数内置了对于整型的格式化

 

 PAT不易,诸君共勉
posted @ 2020-02-18 10:58  秦_殇  阅读(196)  评论(0编辑  收藏  举报