题目描述
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).
输入格式
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.
输出格式
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.
输入样例
-1000000 9
输出样例
-999,991
题意及思路
输入a,b,计算a+b的和,然后每三位后加一个’.’输出
1.先将sum和为负数时输出负号,然后将sum变为正数统一处理
2.to_string()转为字符串
3.当字符串s的长度为3的整数倍时,可以正好每三位输出一个’.’,当不是3的整数倍时,最高位开始距离第一个’.’可能只有1或2位,与字符串长度对3余数对应,满足(i+1)%3==len%3条件即可
C++代码
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,sum;
cin>>a>>b;
sum = a + b;
if( sum < 0 ){
cout<<"-";
sum = -sum;
}
string s = to_string(sum);
int len = s.length();
for(int i = 0 ; i < len ; i++){
cout<<s[i];
if((i+1)%3==len%3&&i!=len-1) cout<<".";
}
return 0;
}