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 −106≤a,b≤106. 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
题目只是要求按照英文格式读出数字,又由于数字范围限制在-10^6~10^6之间,因此可以采用两种做法:
#include
#include
#include
#include
using namespace std;
//思路:先转换再反转添加,
int main()
{
int a,b;
scanf("%d%d",&a,&b);
int c=a+b;
string s=to_string(c);
if(c<0){
printf("-");
s.erase(s.begin());
}
reverse(s.begin(),s.end());
string ans;
for(int i=0;i<(int)s.length();i++){
if(i%3==0&&i!=0){
ans+=",";
ans+=s[i];
}
else ans+=s[i];
}
reverse(ans.begin(),ans.end());
cout<
}
第二种,直接讨论输出","位置:
#include
#include
#include
#include
using namespace std;
int main()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
if(c<0){ //调整负号
printf("-");
c=-c;}
if(c/1000000!=0) printf("%d,%03d,%03d",c/1000000,c/1000%1000,c%1000);
else if(c/1000!=0) printf("%d,%03d",c/1000,c%1000);
else printf("%d",c);
return 0;
}