PAT——1001 A+B Format (20分)

题目: 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
−10^6​​ ≤a,b≤10^​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

代码实现

#include<bits/stdc++.h>

using namespace std;

int main(int argc, char** argv) {
    
    
	int a,b,sum,sum1;
	string s;
	stringstream ss;
	
	cin >> a >> b;
	sum = a+b;
	//先不管负数,都变为正数
	sum1 = abs(sum); 
	// 利用流将整型变为string类型 
	ss << sum1; 
	ss >> s;
	
	// 字符串的长度在变化,先存起来 
	int n=s.length();
	// 插入逗号 
	for(int i=n-3; i>0; i-=3) {
    
    
		s.insert(i,",");
	}
	
	// 负数添加负号 
	if(sum < 0) {
    
    
		s.insert(0,"-");
	}
	cout << s;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44635198/article/details/114032548