首页 > 其他 > 详细

1001 A+B Format (20 point(s))

时间:2019-05-03 21:48:06      阅读:157      评论:0      收藏:0      [点我收藏+]

1001 A+B Format (20 point(s))

题意:

求a+b的和,但是要按指定格式输出。

控制格式的方法是:将计算出的和转化为string来存储,并且获取其长度,从后往前依次插入‘,‘,注意如果结果是负数则终止条件要提前1个

本题学习的技巧有:

1.利用stringstream(注意要include<sstream>)将int转string:(例如将int a 转换为 string s):

stringstream ss;
ss << a;
ss >> s;

2.向string中插入字符串的方法:

s.insert(pos, str),pos是待插入的位置, str是待插入的字符串

完整代码:

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
    int a, b, c;
    string s;
    scanf("%d%d", &a, &b);
    c = a + b;
    stringstream ss;
    ss << c;
    ss >> s;
    int n = s.size();
    int temp = 0;
    if (c < 0) temp = 1; // 注意特判正负号 
    for (int i = n - 3; i > temp; i -= 3) {
        s.insert(i, ","); // string里的insert方法能够很好地对在字符串a里插入另一个字符串b 
    }
    cout << s << endl;
    return 0;
}

 

1001 A+B Format (20 point(s))

原文:https://www.cnblogs.com/Shiko/p/10806629.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!