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

A1001A+Bforamt

时间:2020-02-11 19:26:40      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:字符   put   部分   sep   col   hellip   hit   class   air   

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

思路:

判断sum正负,若为负输出-,然后将sum的绝对值存到字符串c中;遍历c,每三个元素且不是最后一个元素时输出逗号。

问题:

部分测试用例答案错误

解决:

从高位开始每三位加一个,这样最低一组可能不足三个,改成,从低位开始每三位一组。给出的样例太有迷惑性了…

 

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 int main() {
 5     int a, b;
 6     cin >> a >> b;
 7     int sum = a + b;
 8     if (sum < 0)cout << "-";
 9     string c = to_string(abs(sum));
10     int len = c.length();
11     for (int i = 0; i < len; i++) {
12         cout << c [i];
13         if ((i+1) % 3 == len%3 &&i!=len-1)
14             cout << ",";
15     }
16     return 0;
17 }

 

A1001A+Bforamt

标签:字符   put   部分   sep   col   hellip   hit   class   air   

原文地址:https://www.cnblogs.com/PennyXia/p/12296164.html

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