码迷,mamicode.com
首页 > 其他好文 > 详细

1001 A+B Format

时间:2019-03-05 21:35:29      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:include   base   color   stream   minus   htm   class   i+1   unless   

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 10?6??a,b10?6??. 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两个数,计算出其和后,按照从后向前的顺序每三个数之前加一个逗号,最后输出这个数和添加的逗号,如果该数为负,要输出负号。

分析:本题将数字转化成字符串可以减少很多麻烦,先判断该数正负,如果为负则输出负号,利用to_string()函数将数的绝对值转化成字符串。加逗号时,要注意数组下标应该+1,(i+1)% 3要等于length % 3,并且不能在最后添加逗号。

AC code:
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
    long long a, b, c;
    cin >> a >> b;
    if (a + b < 0) cout << "-";
    string str = to_string(abs(a + b));
    for (int i = 0; i < str.length(); ++i) {
        cout << str[i];
        if ((i + 1) % 3 == str.length() % 3 &&
            i != str.length() - 1) cout << ",";
    }
    return 0;
}

 

1001 A+B Format

标签:include   base   color   stream   minus   htm   class   i+1   unless   

原文地址:https://www.cnblogs.com/menglingxin/p/10479496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!