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 1 |
Sample Output: |
-999,991 |
#include<bits/stdc++.h>
using namespace std;
int main(){
long int op1,op2;
long int sum;
cin>>op1>>op2;
sum=op1+op2;
if(sum<0){
cout<<"-";
sum=abs(sum);
}
if(sum==0) cout<<0;
char buf[10]="";
sprintf(buf, "%ld", sum);
int len=strlen(buf);
int m=len/3;
int n=len%3;
int start=0;
if(n==0){
cout<<buf[0]<<buf[1]<<buf[2];
start=3;
m=m-1;
}
else if(n==1){
cout<<buf[0];
start=1;
}
else if(n==2){
cout<<buf[0]<<buf[1];
start=2;
}
while(m!=0){
cout<<",";
cout<<buf[start]<<buf[start+1]<<buf[start+2];
start+=3;
m--;
}
return 0;
}
注意点:
1.数值型数据转换为字符数组有现成函数可调用:
例1: itoa(sum,buf,10);//将数值转换成为字符数组的形式;
但是这条函数在浙大PAT练习系统里面没有,无法通过;
例2: sprintf(buf, “%ld”, sum); 这个就OK.
备注两条:
// 数字转字符串
sprintf(str, “%d”, num);
// 字符串转数字
sscanf(str, “%d”, &rsl);
2.要体会一下这种输出方式的内在逻辑:
本次的思路是分组输出,三个一组,不够的单独输出;
3.还有这一题过检测点的问题,一直是19分
终于找到原因是我直接if(sum==0) cout<<0;
把这条语句去掉之后就OK,输出零的位数会有差别。
但我仍然挺迷这题目也没规定0是怎么处理的哇?
找了好久终于找到,
如果各位大神朋友有什么高见,欢迎评论区讨论!