1001 A+B Format (20 分)
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 −106 ≤a,b≤106 . 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
一开始部分正确(14分)
错误原因:
以为从左开始分组,应该是从右开始。
知识点: to_string函数< string >库
”to_string出错“解决办法: dev c++ “编译选项” 添加-std=c++11
代码:
#include<cstdio>
#include<iostream>
#include<string>
//#include<algorithm>
using namespace std;
//const int maxn=+5;
int main()
{
int a,b,sum;
cin>>a>>b;
sum=a+b;
string s=to_string(sum);//!!to_string!!!! int -> string
for(int i=0;i<s.length();i++)
{
cout<<s[i];
if(s[i]=='-') continue;
if((s.length()-i-1)%3==0 && i!=s.length()-1 && s.length()>3)
cout<<",";
}
return 0;
}