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

1001. A+B Format (20)

时间:2015-02-23 14:20:06      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:pat   c++   

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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,99

方法一:
#include <iostream>
#include <string>
using namespace std;
int n[7];
char c[10];
string intConvertString(int a) {
    string str;
    int i, j = 0, k = 0;
    int temp = 0;
    for(i=0; i<7; i++) {
        n[i] = a%10;
        a /=10;
        if(n[i]!=0) {
            temp = i + 1;
        }
    }
    for(i=0; i<temp; i++) {
        c[j++] = n[i]+'0';
        if((i+1)%3 == 0&&i+1!=temp) {
            c[j++] = ',';
        }
    }
    for(i=0; i<j/2; i++) {
        temp = c[i];
        c[i] = c[j-i-1];
        c[j-i-1] = temp;
    }
    return c;
}
int main() {
    int a, b, sum;
    while(cin>>a>>b) {
        sum = a + b;
        if(sum > 0) {
            cout<<intConvertString(sum)<<endl; 
        } else if(sum < 0){
            cout<<"-"<<intConvertString(-sum)<<endl;
        } else {
            cout<<"0"<<endl;
        }
    }
    return 0;
}


方法二:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    
    int a,b;
    cin>>a>>b;
    int c = a + b;
    stringstream strStream;  
    strStream<<c;            //int转string的方法!
    string s = strStream.str();

    for(int i = s.size() - 3; i > 0 && s[i - 1] != '-'; i -= 3)
        s.insert(i, ",");

    cout<<s<<endl;
} 


1001. A+B Format (20)

标签:pat   c++   

原文地址:http://blog.csdn.net/jason_wang1989/article/details/43916295

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