题目1001 A+B Format

题目1001 A+B Format,第1张

记录学习写博客的第一天(PAT题目)

题目1001 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 −1e6≤a,b≤1e6. 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结果的输出,不过对于结果的输出有一定的格式要求,我们进行特定格式输出即可。


对于计算的结果我们通过C++11中的to_string方法,将计算结果转化为字符串形式,然后依次输出字符,在下标不等于len - 1且满足(i + 1) % 3 == len % 3 时,进行"," 的输出,对于-号直接输出!这道题属于细节题目,要看清样例输出的结果格式,进行特定输出就行啦!

附上C++源代码:

#include 
#include 
using namespace std;

int main()
{
    int a,b;
    cin >> a >> b;
    string s = to_string(a + b);
    int len = s.length();
    for(int i = 0; i < len; i ++)
    {
        cout << s[i];
        if(s[i] == '-') continue;
        if(i != len - 1 && (i + 1) % 3 == len % 3)
        {
        	cout << ",";
        }
    }
    return 0;
}

This is my first blog~    I will try my best!

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/607342.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-14
下一篇 2022-04-14

发表评论

登录后才能评论

评论列表(0条)

保存