原PAT网站用户可在 https://patest.cn/bind_old_pat_user 页面绑定至拼题A账号。绑定后,原PAT网站的提交将被合并至拼题A网站用户的对应题目集中。
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
我的解法:
大体思想:把两个数相加,结果一位一位的转化为字符,在转换为字符的过程中添加逗号
具体看代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int a,b;
while(~scanf("%d %d",&a,&b))
{
string tem;
int c=a+b;
int t=c;
int i=0;
while(t/10!=0) // 判断是否能 对10取余
{
tem+=(abs(t%10)+'0'); //数字转换为字符, 这个地方要加绝对值,否则,负数对10取余是负数,会影响结果
i++;
if(i==3)
{
tem+=',';
i=0;
}
t/=10;
}
tem+=(abs(t%10)+'0'); // 对 最后一位进行处理
if(c<0) //对负数进行处理
tem+='-';
for(i=tem.length()-1;i>=0;i--) // 逆序输出
printf("%c",tem[i]);
printf("\n");
}
return 0;
}
别人的代码:
用了输出流
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int a,b,ans;
string str;
ostringstream stream;
cin>>a>>b;
ans=a+b;
stream<<ans; ///向stream写入数据
str=stream.str();///返回stream所保存的string拷贝
int len=str.size();
if(ans<0) // 对负数进行处理
{
cout<<"-";
len--;
str=str.substr(1,len);
}
for(int i=len-3; i>0; i-=3) // 每隔三位插入一个逗号
{
str.insert(i,",");
}
cout<<str<<endl;
return 0;
}